﻿using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using LibKetoan;
using LibDuoc;

namespace Ketoan
{
	/// <summary>
	/// Summary description for frmImpxuat.
	/// </summary>
	public class frmImpxuat : System.Windows.Forms.Form
	{
		private System.Windows.Forms.Label label1;
		private System.Windows.Forms.Label label2;
		private System.Windows.Forms.Label label3;
		private System.Windows.Forms.Label label5;
		private System.Windows.Forms.DateTimePicker tu;
		private System.Windows.Forms.DateTimePicker den;
		private System.Windows.Forms.TextBox sophieu;
		private System.Windows.Forms.TextBox madv;
		private System.Windows.Forms.DataGrid dataGrid1;
		private System.Windows.Forms.Button butLuu;
		private System.Windows.Forms.Button butKetthuc;
		private System.Windows.Forms.Button butTonghop;
		private doiso.Doisototext doiso=new doiso.Doisototext();
		private int i_userd;
		private string s_mmyy,sql,s_ngay,format_sotien,user,sNoidung;
		private LibKetoan.AccessData a;
        private LibDuoc.AccessData d = new LibDuoc.AccessData();
		private DataSet ds=new DataSet();
		private DataSet dsct=new DataSet();
		private DataSet dsnhom=new DataSet();
		private DataSet dsxml=new DataSet();
		private DataTable dttk=new DataTable();
		private Brush disabledBackBrush;
		private Brush disabledTextBrush;
		private Brush alertBackBrush;
		private Font alertFont;
		private Brush alertTextBrush;
		private Font currentRowFont;
		private Brush currentRowBackBrush;
		private bool afterCurrentCellChanged,bStkhangnam,bClear=true;
		private int checkCol=0,iHoatdong,iLctug,iChuong,iNghiepvu,iLoaibk,iLk,iCapphat,iChucnang=5,iUserid,iTonghop=1,iNhom,iKhoanmucno,iTknonamtruoc;
		private System.Windows.Forms.Label label6;
		private System.Windows.Forms.ComboBox nhom;
		private System.Windows.Forms.DataGrid dataGrid2;
		private System.Windows.Forms.DataGrid dataGrid3;
		private System.Windows.Forms.CheckBox chkAll;
		private System.Windows.Forms.ToolTip toolTip1;
		private System.Windows.Forms.CheckBox chkChitiet;
		private System.Windows.Forms.ComboBox c710;
		private System.Windows.Forms.Label label42;
		private System.Windows.Forms.ComboBox c707;
		private System.Windows.Forms.Label label39;
		private System.Windows.Forms.ComboBox c706;
		private System.Windows.Forms.Label label50;
		private System.Windows.Forms.ComboBox c705;
		private System.Windows.Forms.Label label38;
		private System.Windows.Forms.ComboBox c703;
		private System.Windows.Forms.ComboBox c702;
		private System.Windows.Forms.Label label36;
		private System.Windows.Forms.Label label37;
		private System.Windows.Forms.ComboBox c700;
		private System.Windows.Forms.Label label35;
		private System.Windows.Forms.Label label7;
		private System.Windows.Forms.ComboBox khoanmuc;
		private System.Windows.Forms.ComboBox khoanmuc2;
		private System.Windows.Forms.Label label8;
		private System.Windows.Forms.ComboBox khoanmuc4;
		private System.Windows.Forms.Label label9;
		private System.Windows.Forms.ComboBox khoanmuc3;
		private System.Windows.Forms.Label label10;
		private System.Windows.Forms.CheckBox chkNo;
		private System.Windows.Forms.Button butIn;
		private System.ComponentModel.IContainer components;

		public frmImpxuat(LibKetoan.AccessData acc,string mmyy,string ngay,int userid)
		{
			//
			// Required for Windows Form Designer support
			//
			InitializeComponent();
			a=acc;s_mmyy=mmyy;i_userd=userid;s_ngay=ngay;
			//
			// TODO: Add any constructor code after InitializeComponent call
			//
		}

		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		protected override void Dispose( bool disposing )
		{
			if( disposing )
			{
				if(components != null)
				{
					components.Dispose();
					if(disabledBackBrush != null)
					{
						disabledBackBrush.Dispose();
						disabledTextBrush.Dispose();
						alertBackBrush.Dispose();
						alertFont.Dispose();
						alertTextBrush.Dispose();
						currentRowFont.Dispose();
						currentRowBackBrush.Dispose();
					}
				}
			}
			base.Dispose( disposing );
		}

		#region Windows Form Designer generated code
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
            this.components = new System.ComponentModel.Container();
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(frmImpxuat));
            this.label1 = new System.Windows.Forms.Label();
            this.label2 = new System.Windows.Forms.Label();
            this.label3 = new System.Windows.Forms.Label();
            this.label5 = new System.Windows.Forms.Label();
            this.tu = new System.Windows.Forms.DateTimePicker();
            this.den = new System.Windows.Forms.DateTimePicker();
            this.sophieu = new System.Windows.Forms.TextBox();
            this.madv = new System.Windows.Forms.TextBox();
            this.dataGrid1 = new System.Windows.Forms.DataGrid();
            this.butLuu = new System.Windows.Forms.Button();
            this.butKetthuc = new System.Windows.Forms.Button();
            this.butTonghop = new System.Windows.Forms.Button();
            this.label6 = new System.Windows.Forms.Label();
            this.nhom = new System.Windows.Forms.ComboBox();
            this.dataGrid2 = new System.Windows.Forms.DataGrid();
            this.dataGrid3 = new System.Windows.Forms.DataGrid();
            this.chkAll = new System.Windows.Forms.CheckBox();
            this.toolTip1 = new System.Windows.Forms.ToolTip(this.components);
            this.chkChitiet = new System.Windows.Forms.CheckBox();
            this.c710 = new System.Windows.Forms.ComboBox();
            this.label42 = new System.Windows.Forms.Label();
            this.c707 = new System.Windows.Forms.ComboBox();
            this.label39 = new System.Windows.Forms.Label();
            this.c706 = new System.Windows.Forms.ComboBox();
            this.label50 = new System.Windows.Forms.Label();
            this.c705 = new System.Windows.Forms.ComboBox();
            this.label38 = new System.Windows.Forms.Label();
            this.c703 = new System.Windows.Forms.ComboBox();
            this.c702 = new System.Windows.Forms.ComboBox();
            this.label36 = new System.Windows.Forms.Label();
            this.label37 = new System.Windows.Forms.Label();
            this.c700 = new System.Windows.Forms.ComboBox();
            this.label35 = new System.Windows.Forms.Label();
            this.label7 = new System.Windows.Forms.Label();
            this.khoanmuc = new System.Windows.Forms.ComboBox();
            this.khoanmuc2 = new System.Windows.Forms.ComboBox();
            this.label8 = new System.Windows.Forms.Label();
            this.khoanmuc4 = new System.Windows.Forms.ComboBox();
            this.label9 = new System.Windows.Forms.Label();
            this.khoanmuc3 = new System.Windows.Forms.ComboBox();
            this.label10 = new System.Windows.Forms.Label();
            this.chkNo = new System.Windows.Forms.CheckBox();
            this.butIn = new System.Windows.Forms.Button();
            ((System.ComponentModel.ISupportInitialize)(this.dataGrid1)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.dataGrid2)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.dataGrid3)).BeginInit();
            this.SuspendLayout();
            // 
            // label1
            // 
            this.label1.Location = new System.Drawing.Point(224, 50);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(56, 23);
            this.label1.TabIndex = 24;
            this.label1.Text = "Tử ngày :";
            this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
            this.label1.Click += new System.EventHandler(this.label1_Click);
            // 
            // label2
            // 
            this.label2.Location = new System.Drawing.Point(354, 50);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(16, 23);
            this.label2.TabIndex = 26;
            this.label2.Text = "-";
            this.label2.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
            this.label2.Click += new System.EventHandler(this.label2_Click);
            // 
            // label3
            // 
            this.label3.Location = new System.Drawing.Point(432, 50);
            this.label3.Name = "label3";
            this.label3.Size = new System.Drawing.Size(72, 23);
            this.label3.TabIndex = 28;
            this.label3.Text = "Số phiếu :";
            this.label3.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
            this.label3.Click += new System.EventHandler(this.label3_Click);
            // 
            // label5
            // 
            this.label5.Location = new System.Drawing.Point(600, 50);
            this.label5.Name = "label5";
            this.label5.Size = new System.Drawing.Size(80, 23);
            this.label5.TabIndex = 32;
            this.label5.Text = "Bộ phận :";
            this.label5.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
            this.label5.Click += new System.EventHandler(this.label5_Click);
            // 
            // tu
            // 
            this.tu.CustomFormat = "dd/MM/yyyy";
            this.tu.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.tu.Format = System.Windows.Forms.DateTimePickerFormat.Custom;
            this.tu.Location = new System.Drawing.Point(280, 51);
            this.tu.Name = "tu";
            this.tu.Size = new System.Drawing.Size(80, 21);
            this.tu.TabIndex = 12;
            this.tu.Value = new System.DateTime(2005, 5, 26, 11, 8, 30, 30);
            this.tu.ValueChanged += new System.EventHandler(this.tu_ValueChanged);
            this.tu.KeyDown += new System.Windows.Forms.KeyEventHandler(this.tu_KeyDown);
            // 
            // den
            // 
            this.den.CustomFormat = "dd/MM/yyyy";
            this.den.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.den.Format = System.Windows.Forms.DateTimePickerFormat.Custom;
            this.den.Location = new System.Drawing.Point(368, 51);
            this.den.Name = "den";
            this.den.Size = new System.Drawing.Size(80, 21);
            this.den.TabIndex = 13;
            this.den.ValueChanged += new System.EventHandler(this.den_ValueChanged);
            this.den.KeyDown += new System.Windows.Forms.KeyEventHandler(this.tu_KeyDown);
            // 
            // sophieu
            // 
            this.sophieu.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.sophieu.ForeColor = System.Drawing.Color.Red;
            this.sophieu.Location = new System.Drawing.Point(504, 51);
            this.sophieu.Name = "sophieu";
            this.sophieu.Size = new System.Drawing.Size(120, 21);
            this.sophieu.TabIndex = 229;
            this.sophieu.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
            this.sophieu.TextChanged += new System.EventHandler(this.sophieu_TextChanged);
            this.sophieu.KeyDown += new System.Windows.Forms.KeyEventHandler(this.tu_KeyDown);
            // 
            // madv
            // 
            this.madv.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
                        | System.Windows.Forms.AnchorStyles.Right)));
            this.madv.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.madv.ForeColor = System.Drawing.Color.Red;
            this.madv.Location = new System.Drawing.Point(680, 51);
            this.madv.Name = "madv";
            this.madv.Size = new System.Drawing.Size(104, 21);
            this.madv.TabIndex = 213;
            this.madv.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
            this.madv.TextChanged += new System.EventHandler(this.madv_TextChanged);
            this.madv.KeyDown += new System.Windows.Forms.KeyEventHandler(this.tu_KeyDown);
            // 
            // dataGrid1
            // 
            this.dataGrid1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
                        | System.Windows.Forms.AnchorStyles.Left)
                        | System.Windows.Forms.AnchorStyles.Right)));
            this.dataGrid1.BackgroundColor = System.Drawing.SystemColors.Control;
            this.dataGrid1.BorderStyle = System.Windows.Forms.BorderStyle.None;
            this.dataGrid1.CaptionBackColor = System.Drawing.SystemColors.Control;
            this.dataGrid1.DataMember = "";
            this.dataGrid1.FlatMode = true;
            this.dataGrid1.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.dataGrid1.HeaderForeColor = System.Drawing.SystemColors.ControlText;
            this.dataGrid1.Location = new System.Drawing.Point(8, 58);
            this.dataGrid1.Name = "dataGrid1";
            this.dataGrid1.RowHeaderWidth = 5;
            this.dataGrid1.Size = new System.Drawing.Size(776, 184);
            this.dataGrid1.TabIndex = 124;
            this.dataGrid1.CurrentCellChanged += new System.EventHandler(this.dataGrid1_CurrentCellChanged);
            this.dataGrid1.Navigate += new System.Windows.Forms.NavigateEventHandler(this.dataGrid1_Navigate);
            this.dataGrid1.Click += new System.EventHandler(this.dataGrid1_Click);
            // 
            // butLuu
            // 
            this.butLuu.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
            this.butLuu.Image = ((System.Drawing.Image)(resources.GetObject("butLuu.Image")));
            this.butLuu.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
            this.butLuu.Location = new System.Drawing.Point(318, 490);
            this.butLuu.Name = "butLuu";
            this.butLuu.Size = new System.Drawing.Size(74, 25);
            this.butLuu.TabIndex = 15;
            this.butLuu.Text = "&Cập nhật";
            this.butLuu.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
            this.butLuu.Click += new System.EventHandler(this.butLuu_Click);
            // 
            // butKetthuc
            // 
            this.butKetthuc.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
            this.butKetthuc.Image = ((System.Drawing.Image)(resources.GetObject("butKetthuc.Image")));
            this.butKetthuc.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
            this.butKetthuc.Location = new System.Drawing.Point(482, 490);
            this.butKetthuc.Name = "butKetthuc";
            this.butKetthuc.Size = new System.Drawing.Size(70, 25);
            this.butKetthuc.TabIndex = 16;
            this.butKetthuc.Text = "   &Kết thúc";
            this.butKetthuc.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
            this.butKetthuc.Click += new System.EventHandler(this.butKetthuc_Click);
            // 
            // butTonghop
            // 
            this.butTonghop.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
            this.butTonghop.Image = ((System.Drawing.Image)(resources.GetObject("butTonghop.Image")));
            this.butTonghop.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
            this.butTonghop.Location = new System.Drawing.Point(241, 490);
            this.butTonghop.Name = "butTonghop";
            this.butTonghop.Size = new System.Drawing.Size(74, 25);
            this.butTonghop.TabIndex = 14;
            this.butTonghop.Text = "&Tổng hợp";
            this.butTonghop.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
            this.butTonghop.Click += new System.EventHandler(this.butTonghop_Click);
            // 
            // label6
            // 
            this.label6.Location = new System.Drawing.Point(-5, 50);
            this.label6.Name = "label6";
            this.label6.Size = new System.Drawing.Size(56, 23);
            this.label6.TabIndex = 22;
            this.label6.Text = "Bộ phận :";
            this.label6.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
            this.label6.Click += new System.EventHandler(this.label6_Click);
            // 
            // nhom
            // 
            this.nhom.BackColor = System.Drawing.SystemColors.HighlightText;
            this.nhom.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
            this.nhom.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.nhom.Location = new System.Drawing.Point(48, 51);
            this.nhom.Name = "nhom";
            this.nhom.Size = new System.Drawing.Size(168, 21);
            this.nhom.TabIndex = 11;
            this.nhom.SelectedIndexChanged += new System.EventHandler(this.nhom_SelectedIndexChanged);
            this.nhom.KeyDown += new System.Windows.Forms.KeyEventHandler(this.tu_KeyDown);
            // 
            // dataGrid2
            // 
            this.dataGrid2.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)
                        | System.Windows.Forms.AnchorStyles.Right)));
            this.dataGrid2.BackgroundColor = System.Drawing.SystemColors.Control;
            this.dataGrid2.BorderStyle = System.Windows.Forms.BorderStyle.None;
            this.dataGrid2.CaptionBackColor = System.Drawing.SystemColors.Control;
            this.dataGrid2.CaptionForeColor = System.Drawing.Color.Red;
            this.dataGrid2.CaptionText = "xxx";
            this.dataGrid2.DataMember = "";
            this.dataGrid2.FlatMode = true;
            this.dataGrid2.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.dataGrid2.HeaderForeColor = System.Drawing.SystemColors.ControlText;
            this.dataGrid2.Location = new System.Drawing.Point(8, 242);
            this.dataGrid2.Name = "dataGrid2";
            this.dataGrid2.RowHeaderWidth = 5;
            this.dataGrid2.Size = new System.Drawing.Size(392, 240);
            this.dataGrid2.TabIndex = 127;
            this.dataGrid2.Navigate += new System.Windows.Forms.NavigateEventHandler(this.dataGrid2_Navigate);
            // 
            // dataGrid3
            // 
            this.dataGrid3.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
            this.dataGrid3.BackgroundColor = System.Drawing.SystemColors.Control;
            this.dataGrid3.BorderStyle = System.Windows.Forms.BorderStyle.None;
            this.dataGrid3.CaptionBackColor = System.Drawing.SystemColors.Control;
            this.dataGrid3.CaptionForeColor = System.Drawing.Color.Red;
            this.dataGrid3.CaptionText = "xxx";
            this.dataGrid3.DataMember = "";
            this.dataGrid3.FlatMode = true;
            this.dataGrid3.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.dataGrid3.HeaderForeColor = System.Drawing.SystemColors.ControlText;
            this.dataGrid3.Location = new System.Drawing.Point(404, 242);
            this.dataGrid3.Name = "dataGrid3";
            this.dataGrid3.RowHeaderWidth = 5;
            this.dataGrid3.Size = new System.Drawing.Size(376, 240);
            this.dataGrid3.TabIndex = 128;
            this.dataGrid3.Navigate += new System.Windows.Forms.NavigateEventHandler(this.dataGrid3_Navigate);
            // 
            // chkAll
            // 
            this.chkAll.Appearance = System.Windows.Forms.Appearance.Button;
            this.chkAll.Font = new System.Drawing.Font("Arial", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.chkAll.Location = new System.Drawing.Point(25, 77);
            this.chkAll.Name = "chkAll";
            this.chkAll.Size = new System.Drawing.Size(23, 21);
            this.chkAll.TabIndex = 129;
            this.chkAll.Text = "...";
            this.chkAll.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
            this.toolTip1.SetToolTip(this.chkAll, "Chọn cả");
            this.chkAll.CheckedChanged += new System.EventHandler(this.chkAll_CheckedChanged);
            // 
            // chkChitiet
            // 
            this.chkChitiet.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
            this.chkChitiet.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.chkChitiet.Location = new System.Drawing.Point(7, 484);
            this.chkChitiet.Name = "chkChitiet";
            this.chkChitiet.Size = new System.Drawing.Size(88, 21);
            this.chkChitiet.TabIndex = 30;
            this.chkChitiet.Text = "Hiện chi tiết";
            this.chkChitiet.CheckedChanged += new System.EventHandler(this.chkChitiet_CheckedChanged);
            // 
            // c710
            // 
            this.c710.BackColor = System.Drawing.SystemColors.HighlightText;
            this.c710.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
            this.c710.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.c710.Location = new System.Drawing.Point(48, 5);
            this.c710.Name = "c710";
            this.c710.Size = new System.Drawing.Size(168, 21);
            this.c710.TabIndex = 0;
            this.c710.KeyDown += new System.Windows.Forms.KeyEventHandler(this.tu_KeyDown);
            // 
            // label42
            // 
            this.label42.Location = new System.Drawing.Point(-16, 3);
            this.label42.Name = "label42";
            this.label42.Size = new System.Drawing.Size(64, 23);
            this.label42.TabIndex = 0;
            this.label42.Text = "Nhóm :";
            this.label42.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
            // 
            // c707
            // 
            this.c707.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
            this.c707.BackColor = System.Drawing.SystemColors.HighlightText;
            this.c707.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
            this.c707.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.c707.Location = new System.Drawing.Point(680, 28);
            this.c707.Name = "c707";
            this.c707.Size = new System.Drawing.Size(104, 21);
            this.c707.TabIndex = 10;
            this.c707.SelectedIndexChanged += new System.EventHandler(this.c707_SelectedIndexChanged);
            this.c707.KeyDown += new System.Windows.Forms.KeyEventHandler(this.tu_KeyDown);
            // 
            // label39
            // 
            this.label39.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
            this.label39.Location = new System.Drawing.Point(600, 27);
            this.label39.Name = "label39";
            this.label39.Size = new System.Drawing.Size(80, 23);
            this.label39.TabIndex = 20;
            this.label39.Text = "Cấp phát :";
            this.label39.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
            this.label39.Click += new System.EventHandler(this.label39_Click);
            // 
            // c706
            // 
            this.c706.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
                        | System.Windows.Forms.AnchorStyles.Right)));
            this.c706.BackColor = System.Drawing.SystemColors.HighlightText;
            this.c706.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
            this.c706.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.c706.Location = new System.Drawing.Point(280, 28);
            this.c706.Name = "c706";
            this.c706.Size = new System.Drawing.Size(168, 21);
            this.c706.TabIndex = 8;
            this.c706.SelectedIndexChanged += new System.EventHandler(this.c706_SelectedIndexChanged);
            this.c706.KeyDown += new System.Windows.Forms.KeyEventHandler(this.tu_KeyDown);
            // 
            // label50
            // 
            this.label50.Location = new System.Drawing.Point(208, 27);
            this.label50.Name = "label50";
            this.label50.Size = new System.Drawing.Size(72, 23);
            this.label50.TabIndex = 16;
            this.label50.Text = "Loại khoản :";
            this.label50.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
            this.label50.Click += new System.EventHandler(this.label50_Click);
            // 
            // c705
            // 
            this.c705.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
            this.c705.BackColor = System.Drawing.SystemColors.HighlightText;
            this.c705.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
            this.c705.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.c705.Location = new System.Drawing.Point(504, 28);
            this.c705.Name = "c705";
            this.c705.Size = new System.Drawing.Size(120, 21);
            this.c705.TabIndex = 9;
            this.c705.SelectedIndexChanged += new System.EventHandler(this.c705_SelectedIndexChanged);
            this.c705.KeyDown += new System.Windows.Forms.KeyEventHandler(this.tu_KeyDown);
            // 
            // label38
            // 
            this.label38.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
            this.label38.Location = new System.Drawing.Point(424, 27);
            this.label38.Name = "label38";
            this.label38.Size = new System.Drawing.Size(80, 23);
            this.label38.TabIndex = 18;
            this.label38.Text = "Loại b.kê :";
            this.label38.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
            this.label38.Click += new System.EventHandler(this.label38_Click);
            // 
            // c703
            // 
            this.c703.BackColor = System.Drawing.SystemColors.HighlightText;
            this.c703.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
            this.c703.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.c703.Location = new System.Drawing.Point(48, 28);
            this.c703.Name = "c703";
            this.c703.Size = new System.Drawing.Size(168, 21);
            this.c703.TabIndex = 7;
            this.c703.SelectedIndexChanged += new System.EventHandler(this.c703_SelectedIndexChanged);
            this.c703.KeyDown += new System.Windows.Forms.KeyEventHandler(this.tu_KeyDown);
            // 
            // c702
            // 
            this.c702.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
            this.c702.BackColor = System.Drawing.SystemColors.HighlightText;
            this.c702.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
            this.c702.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.c702.Location = new System.Drawing.Point(680, 5);
            this.c702.Name = "c702";
            this.c702.Size = new System.Drawing.Size(104, 21);
            this.c702.TabIndex = 2;
            this.c702.KeyDown += new System.Windows.Forms.KeyEventHandler(this.tu_KeyDown);
            // 
            // label36
            // 
            this.label36.Location = new System.Drawing.Point(-16, 27);
            this.label36.Name = "label36";
            this.label36.Size = new System.Drawing.Size(64, 23);
            this.label36.TabIndex = 14;
            this.label36.Text = "N. vụ :";
            this.label36.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
            this.label36.Click += new System.EventHandler(this.label36_Click);
            // 
            // label37
            // 
            this.label37.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
            this.label37.Location = new System.Drawing.Point(624, 3);
            this.label37.Name = "label37";
            this.label37.Size = new System.Drawing.Size(56, 23);
            this.label37.TabIndex = 4;
            this.label37.Text = "Chương :";
            this.label37.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
            // 
            // c700
            // 
            this.c700.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
                        | System.Windows.Forms.AnchorStyles.Right)));
            this.c700.BackColor = System.Drawing.SystemColors.HighlightText;
            this.c700.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
            this.c700.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.c700.Location = new System.Drawing.Point(280, 5);
            this.c700.Name = "c700";
            this.c700.Size = new System.Drawing.Size(344, 21);
            this.c700.TabIndex = 1;
            this.c700.KeyDown += new System.Windows.Forms.KeyEventHandler(this.tu_KeyDown);
            // 
            // label35
            // 
            this.label35.Location = new System.Drawing.Point(216, 3);
            this.label35.Name = "label35";
            this.label35.Size = new System.Drawing.Size(64, 23);
            this.label35.TabIndex = 2;
            this.label35.Text = "Hoạt động :";
            this.label35.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
            // 
            // label7
            // 
            this.label7.Enabled = false;
            this.label7.Location = new System.Drawing.Point(783, 558);
            this.label7.Name = "label7";
            this.label7.Size = new System.Drawing.Size(10, 23);
            this.label7.TabIndex = 6;
            this.label7.Text = "K. mục 1 :";
            this.label7.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
            this.label7.Visible = false;
            // 
            // khoanmuc
            // 
            this.khoanmuc.BackColor = System.Drawing.SystemColors.HighlightText;
            this.khoanmuc.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.khoanmuc.Location = new System.Drawing.Point(789, 556);
            this.khoanmuc.Name = "khoanmuc";
            this.khoanmuc.Size = new System.Drawing.Size(10, 21);
            this.khoanmuc.TabIndex = 3;
            this.khoanmuc.Visible = false;
            this.khoanmuc.KeyDown += new System.Windows.Forms.KeyEventHandler(this.tu_KeyDown);
            // 
            // khoanmuc2
            // 
            this.khoanmuc2.BackColor = System.Drawing.SystemColors.HighlightText;
            this.khoanmuc2.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.khoanmuc2.Location = new System.Drawing.Point(786, 558);
            this.khoanmuc2.Name = "khoanmuc2";
            this.khoanmuc2.Size = new System.Drawing.Size(10, 21);
            this.khoanmuc2.TabIndex = 4;
            this.khoanmuc2.Visible = false;
            this.khoanmuc2.KeyDown += new System.Windows.Forms.KeyEventHandler(this.tu_KeyDown);
            // 
            // label8
            // 
            this.label8.Enabled = false;
            this.label8.Location = new System.Drawing.Point(783, 556);
            this.label8.Name = "label8";
            this.label8.Size = new System.Drawing.Size(10, 23);
            this.label8.TabIndex = 8;
            this.label8.Text = "K. mục 2 :";
            this.label8.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
            this.label8.Visible = false;
            // 
            // khoanmuc4
            // 
            this.khoanmuc4.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
            this.khoanmuc4.BackColor = System.Drawing.SystemColors.HighlightText;
            this.khoanmuc4.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.khoanmuc4.Location = new System.Drawing.Point(786, 558);
            this.khoanmuc4.Name = "khoanmuc4";
            this.khoanmuc4.Size = new System.Drawing.Size(10, 21);
            this.khoanmuc4.TabIndex = 6;
            this.khoanmuc4.Visible = false;
            this.khoanmuc4.KeyDown += new System.Windows.Forms.KeyEventHandler(this.tu_KeyDown);
            // 
            // label9
            // 
            this.label9.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
            this.label9.Enabled = false;
            this.label9.Location = new System.Drawing.Point(786, 556);
            this.label9.Name = "label9";
            this.label9.Size = new System.Drawing.Size(10, 23);
            this.label9.TabIndex = 12;
            this.label9.Text = "K. mục 4 :";
            this.label9.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
            this.label9.Visible = false;
            // 
            // khoanmuc3
            // 
            this.khoanmuc3.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
                        | System.Windows.Forms.AnchorStyles.Right)));
            this.khoanmuc3.BackColor = System.Drawing.SystemColors.HighlightText;
            this.khoanmuc3.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.khoanmuc3.Location = new System.Drawing.Point(786, 558);
            this.khoanmuc3.Name = "khoanmuc3";
            this.khoanmuc3.Size = new System.Drawing.Size(10, 21);
            this.khoanmuc3.TabIndex = 5;
            this.khoanmuc3.Visible = false;
            this.khoanmuc3.KeyDown += new System.Windows.Forms.KeyEventHandler(this.tu_KeyDown);
            // 
            // label10
            // 
            this.label10.Enabled = false;
            this.label10.Location = new System.Drawing.Point(783, 558);
            this.label10.Name = "label10";
            this.label10.Size = new System.Drawing.Size(10, 23);
            this.label10.TabIndex = 10;
            this.label10.Text = "K. mục 3 :";
            this.label10.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
            this.label10.Visible = false;
            // 
            // chkNo
            // 
            this.chkNo.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
            this.chkNo.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.chkNo.Location = new System.Drawing.Point(96, 484);
            this.chkNo.Name = "chkNo";
            this.chkNo.Size = new System.Drawing.Size(136, 21);
            this.chkNo.TabIndex = 230;
            this.chkNo.Text = "TK Nợ theo mặt hàng";
            this.chkNo.CheckedChanged += new System.EventHandler(this.chkNo_CheckedChanged);
            // 
            // butIn
            // 
            this.butIn.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
            this.butIn.Image = ((System.Drawing.Image)(resources.GetObject("butIn.Image")));
            this.butIn.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
            this.butIn.Location = new System.Drawing.Point(395, 490);
            this.butIn.Name = "butIn";
            this.butIn.Size = new System.Drawing.Size(84, 25);
            this.butIn.TabIndex = 233;
            this.butIn.Text = "&Phiếu xuất";
            this.butIn.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
            this.butIn.Click += new System.EventHandler(this.butIn_Click);
            // 
            // frmImpxuat
            // 
            this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
            this.ClientSize = new System.Drawing.Size(792, 573);
            this.Controls.Add(this.butIn);
            this.Controls.Add(this.chkNo);
            this.Controls.Add(this.c700);
            this.Controls.Add(this.khoanmuc2);
            this.Controls.Add(this.khoanmuc4);
            this.Controls.Add(this.label9);
            this.Controls.Add(this.khoanmuc3);
            this.Controls.Add(this.label10);
            this.Controls.Add(this.label8);
            this.Controls.Add(this.khoanmuc);
            this.Controls.Add(this.label7);
            this.Controls.Add(this.c703);
            this.Controls.Add(this.c705);
            this.Controls.Add(this.c710);
            this.Controls.Add(this.label42);
            this.Controls.Add(this.c707);
            this.Controls.Add(this.label39);
            this.Controls.Add(this.c706);
            this.Controls.Add(this.label50);
            this.Controls.Add(this.label38);
            this.Controls.Add(this.c702);
            this.Controls.Add(this.label36);
            this.Controls.Add(this.label37);
            this.Controls.Add(this.label35);
            this.Controls.Add(this.chkChitiet);
            this.Controls.Add(this.chkAll);
            this.Controls.Add(this.nhom);
            this.Controls.Add(this.label6);
            this.Controls.Add(this.butTonghop);
            this.Controls.Add(this.butKetthuc);
            this.Controls.Add(this.butLuu);
            this.Controls.Add(this.madv);
            this.Controls.Add(this.sophieu);
            this.Controls.Add(this.den);
            this.Controls.Add(this.tu);
            this.Controls.Add(this.label5);
            this.Controls.Add(this.label3);
            this.Controls.Add(this.label2);
            this.Controls.Add(this.label1);
            this.Controls.Add(this.dataGrid1);
            this.Controls.Add(this.dataGrid2);
            this.Controls.Add(this.dataGrid3);
            this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
            this.KeyPreview = true;
            this.Name = "frmImpxuat";
            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
            this.Text = "Thu nhập chứng từ phiếu xuất kho";
            this.WindowState = System.Windows.Forms.FormWindowState.Maximized;
            this.Load += new System.EventHandler(this.frmImpxuat_Load);
            this.MouseMove += new System.Windows.Forms.MouseEventHandler(this.frmImpxuat_MouseMove);
            ((System.ComponentModel.ISupportInitialize)(this.dataGrid1)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.dataGrid2)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.dataGrid3)).EndInit();
            this.ResumeLayout(false);
            this.PerformLayout();

		}
		#endregion

		private void frmImpxuat_Load(object sender, System.EventArgs e)
		{			
			user=a.user;bStkhangnam=a.bStkhangnam();iTknonamtruoc=a.iTknonamtruoc();
			iHoatdong=a.iHoatdongx();iLctug=a.iLctugx();iChuong=a.iChuongx();iNghiepvu=a.iNghiepvux();iLoaibk=a.iLoaibkx();
			iLk=a.iLkx();iCapphat=a.iCapphatx();sNoidung=a.sNoidungx();iUserid=a.iUseridx();iNhom=a.iNhomx();iKhoanmucno=a.iKhoanmucnox();

			dataGrid2.CaptionText=dataGrid3.CaptionText="";
			c700.DisplayMember="TEN";
			c700.ValueMember="ID";
			c700.DataSource=a.get_data("select * from a_hoatdong where sudung=1 order by stt").Tables[0];
			c700.SelectedValue=iHoatdong;

			c702.DisplayMember="TEN";
			c702.ValueMember="ID";
			c702.DataSource=a.get_data("select * from a_dmchuong where sudung=1 order by stt").Tables[0];
			c702.SelectedValue=iChuong;

			c703.DisplayMember="TEN";
			c703.ValueMember="ID";
			c703.DataSource=a.get_data("select * from a_nghiepvu where sudung=1 order by stt").Tables[0];
			c703.SelectedValue=iNghiepvu;	
	
			c705.DisplayMember="TEN";
			c705.ValueMember="ID";
			c705.DataSource=a.get_data("select * from a_dmloaibk where sudung=1 order by stt").Tables[0];
			c705.SelectedValue=iLoaibk;
            
			c706.DisplayMember="LK";
			c706.ValueMember="ID";
			c706.DataSource=a.get_data("select id,lk||' '||tlk as lk,tlk from a_dmlk order by stt").Tables[0];
			c706.SelectedValue=iLk;

			c707.DisplayMember="TEN";
			c707.ValueMember="ID";
			c707.DataSource=a.get_data("select * from a_dmcapphat where sudung=1 order by stt").Tables[0];
			c707.SelectedValue=iCapphat;

			c710.DisplayMember="TEN";
			c710.ValueMember="ID";
			c710.DataSource=a.get_data("select * from a_dmnhombc order by stt").Tables[0];
			c710.SelectedValue=iNhom;

			nhom.DisplayMember="TEN";
			nhom.ValueMember="ID";
			nhom.DataSource=a.get_data("select * from "+d.user+".d_dmnhomkho order by stt").Tables[0];

			khoanmuc.DisplayMember="TEN";
			khoanmuc.ValueMember="ID";
			khoanmuc.DataSource=a.get_data("select * from a_dmkhoanmuc where sudung=1 order by loaikm,stt").Tables[0];
			khoanmuc.SelectedValue=iKhoanmucno;

			khoanmuc2.DisplayMember="TEN";
			khoanmuc2.ValueMember="ID";
			khoanmuc2.DataSource=a.get_data("select * from a_dmkhoanmuc where sudung=1 order by loaikm,stt").Tables[0];

			khoanmuc3.DisplayMember="TEN";
			khoanmuc3.ValueMember="ID";
			khoanmuc3.DataSource=a.get_data("select * from a_dmkhoanmuc where sudung=1 order by loaikm,stt").Tables[0];

			khoanmuc4.DisplayMember="TEN";
			khoanmuc4.ValueMember="ID";
			khoanmuc4.DataSource=a.get_data("select * from a_dmkhoanmuc where sudung=1 order by loaikm,stt").Tables[0];

			tu.Value=new DateTime(2000+int.Parse(s_mmyy.Substring(2,2)),int.Parse(s_mmyy.Substring(0,2)),1,0,0,0);
			den.Value=new DateTime(int.Parse(s_ngay.Substring(6,4)),int.Parse(s_ngay.Substring(3,2)),int.Parse(s_ngay.Substring(0,2)),0,0,0);
			ds.ReadXml("..\\..\\..\\xml\\d_thanhtoan.xml");
			ds.Tables[0].Columns.Add("nguon");
			ds.Tables[0].Columns.Add("kho");
			ds.Tables[0].Columns.Add("chon",typeof(bool));
			ds.Tables[0].Columns.Add("macongno",typeof(decimal));
			ds.Tables[0].Columns.Add("stkkho",typeof(decimal));
			ds.Tables[0].Columns.Add("tcnkp",typeof(decimal));
			ds.Tables[0].Columns.Add("userid",typeof(decimal));
			ds.Tables[0].Columns.Add("tablell");
			ds.Tables[0].Columns.Add("tablect");
			ds.Tables[0].Columns.Add("khoa");
			ds.Tables[0].Columns.Add("loai",typeof(decimal));
			ds.Tables[0].Columns.Add("makhoa",typeof(decimal));
			ds.Tables[0].Columns.Add("makho",typeof(decimal));
			ds.Tables[0].Columns.Add("manguon",typeof(decimal));
			ds.Tables[0].Columns.Add("tkno",typeof(decimal));
			ds.Tables[0].Columns.Add("tknosave",typeof(decimal));
			ds.Tables[0].Columns.Add("ttkno");
			ds.Tables[0].Columns.Add("ttknosave");

			load_grid();
			AddGridTableStyle();
			
			this.disabledBackBrush = new SolidBrush(Color.FromArgb(255,255,192));
			this.disabledTextBrush = new SolidBrush(Color.FromArgb(255,0,0));

			this.alertBackBrush = new SolidBrush(SystemColors.HotTrack);
			this.alertFont = new Font(this.dataGrid1.Font.Name, this.dataGrid1.Font.Size, FontStyle.Bold);
			this.alertTextBrush = new SolidBrush(Color.White);
			
			this.currentRowFont = new Font(this.dataGrid1.Font.Name, this.dataGrid1.Font.Size, FontStyle.Regular);
			this.currentRowBackBrush = new SolidBrush(Color.FromArgb(0,255, 255));		

			dttk=a.get_data("select * from a_dmtk order by stk").Tables[0];

			string _mmyy=s_mmyy;
			if (!d.bMmyy(_mmyy))
			{
                foreach (DataRow r in a.get_data("select * from " + d.user + ".tables order by substr(mmyy,3,2) desc,substr(mmyy,1,2) desc").Tables[0].Rows)
				{
					_mmyy=r["mmyy"].ToString();break;
				}
			}
			load_ct(_mmyy,3,0,0,0,-1,"");
			AddGridTableStyle1();
			AddGridTableStyle2();

			chkChitiet.Checked=a.Thongso("impctx")=="1";
			chkNo.Checked=a.Thongso("impctxnoct")=="1";
			chkNo.Enabled=chkChitiet.Checked;
		}

		private void load_ct(string mmyy,int loai,int makho,int manguon,int makhoa,long id,string ngay)
		{
			if (id==-1 || chkChitiet.Checked)
			{
				string ll=d.user+mmyy+".",ct=d.user+mmyy+".",ttkno="";
				try
				{
					ttkno=dataGrid1[dataGrid1.CurrentCell.RowNumber,12].ToString();
				}
				catch{}
				switch (loai)
				{
					case 0: ll+="d_xuatsdll";ct+="d_thucxuat";break;
					case 1: ll+="d_ngtrull";ct+="d_ngtruct";break;
					case 2: ll+="bhytkb";ct+="bhytthuoc";break;
					case 3: ll+="d_xuatll";ct+="d_xuatct";break;
				}
				if (loai==3)
				{
					sql="select '"+mmyy+"' as mmyy,"+loai+" as loai,'xx/xx/xxxx' as ngay,"+id+" as idct,f.id,b.ma,trim(b.ten)||' '||b.hamluong as ten,";
					sql+=" b.dang,c.ten as tenhang,d.ten as tennuoc,sum(ct.soluong) as soluong,";
					sql+=" sum(0) as dongia,sum(ct.soluong*t.giamua) as sotien,0 as tkno,'' as ttkno,'' as ttknosave ";
					sql+=" from "+ll+" a,"+ct+" ct,"+d.user+".d_dmbd b,"+d.user+".d_dmhang c,"+d.user+".d_dmnuoc d,"+d.user+mmyy+".d_theodoi t,"+d.user+".d_dmnhomkt e,"+user+".a_dmtk f ";
					sql+=" where a.id=ct.id and ct.mabd=b.id and b.mahang=c.id and b.manuoc=d.id and ct.sttt=t.id and b.sotk=e.id and e.ma=f.stk ";
					//sql+=" and a.id="+id+" and ct.manguon="+manguon;
                    sql += " and a.id=" + id;
					sql+=" group by f.id,b.ma,trim(b.ten)||' '||b.hamluong,b.dang,c.ten,d.ten";
					sql+=" order by ma";
				}
				else
				{
					sql="select '"+mmyy+"' as mmyy,"+loai+" as loai,to_char(a.ngay,'dd/mm/yyyy') as ngay,0 as idct,f.id,b.ma,trim(b.ten)||' '||b.hamluong as ten,";
					sql+=" b.dang,c.ten as tenhang,d.ten as tennuoc,sum(ct.soluong) as soluong,";
					sql+="sum(0) as dongia,sum(ct.soluong*t.giamua) as sotien,0 as tkno,'' as ttkno,'' as ttknosave ";
					sql+=" from "+ll+" a,"+ct+" ct,"+d.user+".d_dmbd b,"+d.user+".d_dmhang c,"+d.user+".d_dmnuoc d,"+d.user+mmyy+".d_theodoi t,"+d.user+".d_dmnhomkt e,"+user+".a_dmtk f";
					sql+=" where a.id=ct.id and ct.mabd=b.id and b.mahang=c.id and b.manuoc=d.id and ct.sttt=t.id and b.sotk=e.id and e.ma=f.stk";
					sql+=" and to_char(a.ngay,'dd/mm/yyyy')='"+ngay+"'";
					if (loai==0)
					{
						sql+=" and a.makhoa="+makhoa+" and a.loai<>3";
						//sql+=" and ct.makho="+makho+" and ct.manguon="+manguon;
                        sql += " and ct.makho=" + makho;
					}
					else
					{
						if (loai==2) sql+=" and a.maphu="+makhoa;
						else if (loai==1) sql+=" and a.loai="+makhoa;
						//sql+=" and ct.makho="+makho+" and ct.manguon="+manguon;
                        sql += " and ct.makho=" + makho;
					}
					sql+=" group by to_char(a.ngay,'dd/mm/yyyy'),f.id,b.ma,trim(b.ten)||' '||b.hamluong,b.dang,c.ten,d.ten";
					sql+=" order by ma";
				}
				dsct=a.get_data(sql);
				if (loai==0)
				{
					sql="select f.id,b.ma,trim(b.ten)||' '||b.hamluong as ten,";
					sql+=" b.dang,c.ten as tenhang,d.ten as tennuoc,sum(-1*ct.soluong) as soluong,";
					sql+=" sum(0) as dongia,sum(-1*ct.soluong*t.giamua) as sotien,0 as tkno,'' as ttkno ";
					sql+=" from "+ll+" a,"+ct+" ct,"+d.user+".d_dmbd b,"+d.user+".d_dmhang c,"+d.user+".d_dmnuoc d,"+d.user+mmyy+".d_theodoi t,"+d.user+".d_dmnhomkt e,"+user+".a_dmtk f ";
					sql+=" where a.id=ct.id and ct.mabd=b.id and b.mahang=c.id and b.manuoc=d.id and ct.sttt=t.id and b.sotk=e.id and e.ma=f.stk";
					sql+=" and to_char(a.ngay,'dd/mm/yyyy')='"+ngay+"' and a.loai=3";
					sql+=" and a.makhoa="+makhoa;
					//sql+=" and ct.makho="+makho+" and ct.manguon="+manguon;
                    sql += " and ct.makho=" + makho;
					sql+=" group by f.id,b.ma,trim(b.ten)||' '||b.hamluong,b.dang,c.ten,d.ten";
					sql+=" order by ma";
					DataRow r1,r2;
					DataRow [] dr;
					foreach(DataRow r in a.get_data(sql).Tables[0].Rows)
					{
						r1=a.getrowbyid(dsct.Tables[0],"ma='"+r["ma"].ToString()+"' and id="+long.Parse(r["id"].ToString()));
						if (r1==null)
						{
							r2=dsct.Tables[0].NewRow();
							r2["id"]=r["id"].ToString();
							r2["ma"]=r["ma"].ToString();
							r2["ten"]=r["ten"].ToString();
							r2["dang"]=r["dang"].ToString();
							r2["tenhang"]=r["tenhang"].ToString();
							r2["tennuoc"]=r["tennuoc"].ToString();
							r2["soluong"]=r["soluong"].ToString();
							r2["sotien"]=r["sotien"].ToString();
							dsct.Tables[0].Rows.Add(r2);
						}
						else
						{
							dr=dsct.Tables[0].Select("ma='"+r["ma"].ToString()+"'");
							if (dr.Length>0)
							{
								dr[0]["soluong"]=decimal.Parse(dr[0]["soluong"].ToString())+decimal.Parse(r["soluong"].ToString());
								dr[0]["sotien"]=decimal.Parse(dr[0]["sotien"].ToString())+decimal.Parse(r["sotien"].ToString());
							}
						}

					}
				}
				foreach(DataRow r in dsct.Tables[0].Rows)
				{
					r["dongia"]=(decimal.Parse(r["soluong"].ToString())!=0)?decimal.Parse(r["sotien"].ToString())/decimal.Parse(r["soluong"].ToString()):0;
					r["ttknosave"]=r["ttkno"]=ttkno;
					foreach(DataRow r2 in a.get_data("select * from a_impxuatct where mmyy='"+mmyy+"' and idct="+long.Parse(r["idct"].ToString())+" and loai="+loai+" and ngay='"+r["ngay"].ToString()+"' and ma='"+r["ma"].ToString()+"'").Tables[0].Rows)
						r["ttkno"]=r["ttknosave"]=r2["ttkno"].ToString();
				}
				dataGrid2.DataSource=dsct.Tables[0];
				CurrencyManager cm = (CurrencyManager)BindingContext[dataGrid2.DataSource,dataGrid2.DataMember]; 
				DataView dv = (DataView) cm.List; 
				dv.AllowNew = false; 
				load_nhom(mmyy,loai,makho,manguon,makhoa,id,ll,ct,ngay);
			}
			try
			{
				string s="Số phiếu : "+dataGrid1[dataGrid1.CurrentCell.RowNumber,9].ToString()+" ngày "+dataGrid1[dataGrid1.CurrentCell.RowNumber,10].ToString();
				dataGrid2.CaptionText=dataGrid3.CaptionText=s;
			}
			catch{}
		}

		private void load_nhom(string mmyy,int loai,int makho,int manguon,int makhoa,long id,string ll,string ct,string ngay)
		{
			if (loai==3)
			{
				sql="select e.ma,e.ten,sum(a.soluong*t.giamua) as sotien ";
				sql+=" from "+ll+" ll,"+ct+" a,"+d.user+".d_dmbd b,"+d.user+".d_dmhang c,"+d.user+".d_dmnuoc d,"+d.user+".d_dmnhomkt e,"+d.user+mmyy+".d_theodoi t";
				sql+=" where ll.id=a.id and a.mabd=b.id and b.mahang=c.id and b.manuoc=d.id and a.sttt=t.id ";
				//sql+=" and b.sotk=e.id(+) and a.id="+id+" and a.manguon="+manguon+" group by e.ma,e.ten order by e.ma,e.ten";
                sql += " and b.sotk=e.id(+) and a.id=" + id + " group by e.ma,e.ten order by e.ma,e.ten";
			}
			else
			{
				
				sql="select e.ma,e.ten,sum(a.soluong*t.giamua) as sotien ";
				sql+=" from "+ll+" ll,"+ct+" a,"+d.user+".d_dmbd b,"+d.user+".d_dmhang c,"+d.user+".d_dmnuoc d,"+d.user+".d_dmnhomkt e,"+d.user+mmyy+".d_theodoi t";
				sql+=" where ll.id=a.id and a.mabd=b.id and b.mahang=c.id and b.manuoc=d.id and a.sttt=t.id ";
				sql+=" and b.sotk=e.id(+) ";
				sql+=" and to_char(ll.ngay,'dd/mm/yyyy')='"+ngay+"'";
				if (loai==0)
				{
					sql+=" and ll.makhoa="+makhoa+" and ll.loai<>3";
					//sql+=" and a.makho="+makho+" and a.manguon="+manguon;
                    sql += " and a.makho=" + makho;
				}
				else
				{
					if (loai==2) sql+=" and ll.maphu="+makhoa;
					else if (loai==1) sql+=" and ll.loai="+makhoa;
					//sql+=" and a.makho="+makho+" and a.manguon="+manguon;
                    sql += " and a.makho=" + makho;
				}
				sql+=" group by e.ma,e.ten order by e.ma,e.ten";				
			}
			dsnhom=a.get_data(sql);
			if (loai==0)
			{
				sql="select e.ma,e.ten,sum(-1*a.soluong*t.giamua) as sotien ";
				sql+=" from "+ll+" ll,"+ct+" a,"+d.user+".d_dmbd b,"+d.user+".d_dmhang c,"+d.user+".d_dmnuoc d,"+d.user+".d_dmnhomkt e,"+d.user+mmyy+".d_theodoi t";
				sql+=" where ll.id=a.id and a.mabd=b.id and b.mahang=c.id and b.manuoc=d.id and a.sttt=t.id ";
				sql+=" and b.sotk=e.id(+) ";
				sql+=" and to_char(ll.ngay,'dd/mm/yyyy')='"+ngay+"'";
				if (loai==0)
				{
					sql+=" and ll.makhoa="+makhoa+" and ll.loai=3";
					//sql+=" and a.makho="+makho+" and a.manguon="+manguon;
                    sql += " and a.makho=" + makho;
				}
				else
				{
					if (loai==2) sql+=" and ll.maphu="+makhoa;
					else if (loai==1) sql+=" and ll.loai="+makhoa;
					//sql+=" and a.makho="+makho+" and a.manguon="+manguon;
                    sql += " and a.makho=" + makho;
				}
				sql+=" group by e.ma,e.ten order by e.ma,e.ten";
				DataRow r1,r2;
				DataRow [] dr;
				foreach(DataRow r in a.get_data(sql).Tables[0].Rows)
				{
					sql=" ma='"+r["ma"].ToString()+"' and ten='"+r["ten"].ToString()+"'";
					r1=a.getrowbyid(dsnhom.Tables[0],sql);
					if (r1==null)
					{
						r2=dsnhom.Tables[0].NewRow();
						r2["ma"]=r["ma"].ToString();
						r2["ten"]=r["ten"].ToString();
						r2["sotien"]=r["sotien"].ToString();
						dsnhom.Tables[0].Rows.Add(r2);
					}
					else
					{
						dr=dsnhom.Tables[0].Select(sql);
						if (dr.Length>0)
							dr[0]["sotien"]=decimal.Parse(dr[0]["sotien"].ToString())+decimal.Parse(r["sotien"].ToString());
					}
				}
			}
			dataGrid3.DataSource=dsnhom.Tables[0];
			CurrencyManager cm = (CurrencyManager)BindingContext[dataGrid3.DataSource,dataGrid3.DataMember]; 
			DataView dv = (DataView) cm.List; 
			dv.AllowNew = false; 
		}

		private void AddGridTableStyle1()
		{
			DataGridTableStyle ts =new DataGridTableStyle();
			ts.MappingName = dsct.Tables[0].TableName;
			ts.AlternatingBackColor = Color.Beige;
			ts.BackColor = Color.GhostWhite;
			ts.ForeColor = Color.MidnightBlue;
			ts.GridLineColor = Color.RoyalBlue;
			ts.HeaderBackColor = Color.MidnightBlue;
			ts.HeaderForeColor = Color.Lavender;
			ts.SelectionBackColor = Color.Teal;
			ts.SelectionForeColor = Color.PaleGreen;
			ts.ReadOnly=false;
			ts.RowHeaderWidth=10;
						
			DataGridTextBoxColumn TextCol=new DataGridTextBoxColumn();
			TextCol.MappingName = "ttkno";
			TextCol.HeaderText = "TK Nợ";
			TextCol.Width = 80;
			ts.GridColumnStyles.Add(TextCol);
			dataGrid2.TableStyles.Add(ts);

			TextCol=new DataGridTextBoxColumn();
			TextCol.MappingName = "ma";
			TextCol.HeaderText = "Mã số";
			TextCol.Width = 50;
			TextCol.ReadOnly=true;
			ts.GridColumnStyles.Add(TextCol);
			dataGrid2.TableStyles.Add(ts);

			TextCol=new DataGridTextBoxColumn();
			TextCol.MappingName = "ten";
			TextCol.HeaderText = "Tên";
			TextCol.Width = 150;
			TextCol.ReadOnly=true;
			ts.GridColumnStyles.Add(TextCol);
			dataGrid2.TableStyles.Add(ts);

			TextCol=new DataGridTextBoxColumn();
			TextCol.MappingName = "dang";
			TextCol.HeaderText = "ĐVT";
			TextCol.Width = 50;
			TextCol.ReadOnly=true;
			ts.GridColumnStyles.Add(TextCol);
			dataGrid2.TableStyles.Add(ts);

			TextCol=new DataGridTextBoxColumn();
			TextCol.MappingName = "soluong";
			TextCol.HeaderText = "Số lượng";
			TextCol.Width = 50;
			TextCol.Format="### ### ##0.00";
			TextCol.ReadOnly=true;
			TextCol.Alignment=HorizontalAlignment.Right;
			ts.GridColumnStyles.Add(TextCol);
			dataGrid2.TableStyles.Add(ts);

			TextCol=new DataGridTextBoxColumn();
			TextCol.MappingName = "dongia";
			TextCol.HeaderText = "Đơn giá";
			TextCol.Width = 70;
			TextCol.Format="### ### ### ##0.00";
			TextCol.ReadOnly=true;
			TextCol.Alignment=HorizontalAlignment.Right;
			ts.GridColumnStyles.Add(TextCol);
			dataGrid2.TableStyles.Add(ts);

			TextCol=new DataGridTextBoxColumn();
			TextCol.MappingName = "sotien";
			TextCol.HeaderText = "Số tiền";
			TextCol.Width = 80;
			TextCol.Format="### ### ### ### ##0.00";
			TextCol.ReadOnly=true;
			TextCol.Alignment=HorizontalAlignment.Right;
			ts.GridColumnStyles.Add(TextCol);
			dataGrid2.TableStyles.Add(ts);

			TextCol=new DataGridTextBoxColumn();
			TextCol.MappingName = "tenhang";
			TextCol.HeaderText = "Hãng";
			TextCol.Width = 100;
			TextCol.ReadOnly=true;
			ts.GridColumnStyles.Add(TextCol);
			dataGrid2.TableStyles.Add(ts);

			TextCol=new DataGridTextBoxColumn();
			TextCol.MappingName = "tennuoc";
			TextCol.HeaderText = "Nước";
			TextCol.Width = 100;
			TextCol.ReadOnly=true;
			ts.GridColumnStyles.Add(TextCol);
			dataGrid2.TableStyles.Add(ts);
		}

		private void AddGridTableStyle2()
		{
			DataGridTableStyle ts =new DataGridTableStyle();
			ts.MappingName = dsnhom.Tables[0].TableName;
			ts.AlternatingBackColor = Color.Beige;
			ts.BackColor = Color.GhostWhite;
			ts.ForeColor = Color.MidnightBlue;
			ts.GridLineColor = Color.RoyalBlue;
			ts.HeaderBackColor = Color.MidnightBlue;
			ts.HeaderForeColor = Color.Lavender;
			ts.SelectionBackColor = Color.Teal;
			ts.SelectionForeColor = Color.PaleGreen;
			ts.ReadOnly=false;
			ts.RowHeaderWidth=10;
						
			DataGridTextBoxColumn TextCol=new DataGridTextBoxColumn();
			TextCol.MappingName = "ma";
			TextCol.HeaderText = "Số tài khoản";
			TextCol.Width = 80;
			ts.GridColumnStyles.Add(TextCol);
			dataGrid3.TableStyles.Add(ts);

			TextCol=new DataGridTextBoxColumn();
			TextCol.MappingName = "ten";
			TextCol.HeaderText = "Tên tài khoản";
			TextCol.Width = 175;
			ts.GridColumnStyles.Add(TextCol);
			dataGrid3.TableStyles.Add(ts);

			TextCol=new DataGridTextBoxColumn();
			TextCol.MappingName = "sotien";
			TextCol.HeaderText = "Số tiền";
			TextCol.Width = 100;
			TextCol.Format="### ### ### ### ##0.00";
			TextCol.Alignment=HorizontalAlignment.Right;
			ts.GridColumnStyles.Add(TextCol);
			dataGrid3.TableStyles.Add(ts);
		}

		private void load_grid()
		{
			ds.Clear();dsct.Clear();
			DateTime dt1=a.StringToDate(tu.Text).AddDays(-a.iNgaykiemke);
			DateTime dt2=a.StringToDate(den.Text).AddDays(a.iNgaykiemke);
			int y1=dt1.Year,m1=dt1.Month;
			int y2=dt2.Year,m2=dt2.Month;
			int itu,iden;
			string mmyy="";
			for(int i=y1;i<=y2;i++)
			{
				itu=(i==y1)?m1:1;
				iden=(i==y2)?m2:12;
				for(int j=itu;j<=iden;j++)
				{
					mmyy=j.ToString().PadLeft(2,'0')+i.ToString().Substring(2,2);
					if (d.bMmyy(mmyy))
					{
                        ////xuat khac
                        //sql="select distinct 3 as loai,'d_xuatll' as ll,'d_xuatct' as ct,a.id,a.sophieu||'/'||to_char(b.manguon)||to_char(a.khox) as sophieu,";                        
                        //sql+="to_char(a.ngay,'dd/mm/yyyy') as ngay,";
                        //sql+="e.ten as nguon,d.ten as kho,'' as khoa,0 as makhoa,c.ten as ghichu,";
                        //sql+="e.tkno,nvl(e.ketoan,1) as tcnkp,d.useridkt,a.khox as makho,b.manguon,b.ketoan";
                        //sql+=" from "+d.user+mmyy+".d_xuatll a,"+d.user+mmyy+".d_xuatct b,"+d.user+".d_dmkhac c,";
                        //sql+=d.user+".d_dmkho d,"+d.user+".d_dmnguon e,"+user+".a_dmtk f";
                        //sql+=" where a.id=b.id and a.khon=c.id and a.khox=d.id and a.loai='XK' ";
                        ////sql+=" and a.nhom="+int.Parse(nhom.SelectedValue.ToString())+" and b.manguon=e.id(+) ";
                        //sql += " and a.nhom=" + int.Parse(nhom.SelectedValue.ToString());
                        //sql += " and e.tkno=f.id(+) ";
                        //sql+=" and to_date(a.ngay,'dd/mm/yy') between to_date('"+tu.Text+"','dd/mm/yy') and to_date('"+den.Text+"','dd/mm/yy')";
                        ////bhyt
                        //sql+=" union all ";
                        //sql+="select distinct 2 as loai,'bhytkb' as ll,'bhytthuoc' as ct,0 as id,to_char(a.maphu)||to_char(b.manguon)||to_char(b.makho)||'/'||to_char(a.ngay,'ddmm') as sophieu,";
                        //sql+="to_char(a.ngay,'dd/mm/yyyy') as ngay,";
                        //sql+="e.ten as nguon,d.ten as kho,'' as khoa,a.maphu as makhoa,c.doituong as ghichu,";
                        //sql += "e.tkno,nvl(e.ketoan,1) as tcnkp,d.useridkt,b.makho,b.manguon,b.ketoan";
                        //sql+=" from "+d.user+mmyy+".bhytkb a,"+d.user+mmyy+".bhytthuoc b,"+d.user+".d_doituong c,";
                        //sql+=d.user+".d_dmkho d,"+d.user+".d_dmnguon e,"+user+".a_dmtk f";
                        //sql+=" where a.id=b.id and a.maphu=c.madoituong and b.makho=d.id ";
                        //sql+=" and a.nhom="+int.Parse(nhom.SelectedValue.ToString())+" and b.manguon=e.id(+) ";
                        //sql += " and e.tkno=f.id(+) ";
                        //sql+=" and to_date(a.ngay,'dd/mm/yy') between to_date('"+tu.Text+"','dd/mm/yy') and to_date('"+den.Text+"','dd/mm/yy')";
                        ////ngoai tru
                        //sql+=" union all ";
                        //sql+="select distinct 1 as loai,'d_ngtrull' as ll,'d_ngtruct' as ct,0 as id,a.mabn||to_char(b.manguon)||to_char(b.makho)||'/'||to_char(a.ngay,'ddmm') as sophieu,";
                        //sql+="to_char(a.ngay,'dd/mm/yyyy') as ngay,";
                        //sql+="e.ten as nguon,d.ten as kho,'' as khoa,a.loai as makhoa,c.ten as ghichu,";
                        //sql += "e.tkno,nvl(e.ketoan,1) as tcnkp,d.useridkt,b.makho,b.manguon,b.ketoan";
                        //sql+=" from "+d.user+mmyy+".d_ngtrull a,"+d.user+mmyy+".d_ngtruct b,"+d.user+".d_dmloaint c,";
                        //sql+=d.user+".d_dmkho d,"+d.user+".d_dmnguon e,"+user+".a_dmtk f";
                        //sql+=" where a.id=b.id and a.loai=c.id(+) and b.makho=d.id ";
                        //sql+=" and a.nhom="+int.Parse(nhom.SelectedValue.ToString())+" and b.manguon=e.id(+) ";
                        //sql += " and e.tkno=f.id(+) ";
                        //sql+=" and to_date(a.ngay,'dd/mm/yy') between to_date('"+tu.Text+"','dd/mm/yy') and to_date('"+den.Text+"','dd/mm/yy')";
                        ////xuatsd
                        //sql+=" union all ";
                        //sql+="select distinct 0 as loai,'d_xuatsdll' as ll,'d_thucxuat' as ct,0 as id,to_char(a.makhoa)||to_char(b.manguon)||to_char(b.makho)||'/'||to_char(a.ngay,'ddmm') as sophieu,";
                        //sql+="to_char(a.ngay,'dd/mm/yyyy') as ngay,";
                        //sql+="e.ten as nguon,d.ten as kho,'' as khoa,a.makhoa,c.ten as ghichu,";
                        //sql += "e.tkno,nvl(e.ketoan,1) as tcnkp,d.useridkt,b.makho,b.manguon,b.ketoan";
                        //sql+=" from "+d.user+mmyy+".d_xuatsdll a,"+d.user+mmyy+".d_thucxuat b,"+d.user+".d_duockp c,";
                        //sql+=d.user+".d_dmkho d,"+d.user+".d_dmnguon e,"+user+".a_dmtk f";
                        //sql+=" where a.id=b.id and a.makhoa=c.id(+) and b.makho=d.id ";
                        //sql+=" and a.nhom="+int.Parse(nhom.SelectedValue.ToString())+" and b.manguon=e.id(+) ";
                        //sql += " and e.tkno=f.id(+) ";
                        //sql+=" and to_date(a.ngay,'dd/mm/yy') between to_date('"+tu.Text+"','dd/mm/yy') and to_date('"+den.Text+"','dd/mm/yy')";
                        //xuat khac
                        sql = "select distinct 3 as loai,'d_xuatll' as ll,'d_xuatct' as ct,a.id,a.sophieu||to_char(a.khox) as sophieu,";
                        sql += "to_char(a.ngay,'dd/mm/yyyy') as ngay,";
                        sql += "e.ten as nguon,d.ten as kho,'' as khoa,0 as makhoa,c.ten as ghichu,";
                        sql += "e.stk,nvl(e.ketoan,1) as tcnkp,d.useridkt,a.khox as makho,b.ketoan";
                        sql += " from " + d.user + mmyy + ".d_xuatll a," + d.user + mmyy + ".d_xuatct b," + d.user + ".d_dmkhac c,";
                        sql += d.user + ".d_dmkho d," + d.user + ".d_dmnguon e," + user + ".a_dmtk f";
                        sql += " where a.id=b.id and a.khon=c.id and a.khox=d.id and a.loai='XK' ";
                        //sql+=" and a.nhom="+int.Parse(nhom.SelectedValue.ToString())+" and b.manguon=e.id(+) ";
                        sql += " and a.nhom=" + int.Parse(nhom.SelectedValue.ToString());
                        sql += " and e.stk=f.id(+) ";
                        sql += " and to_date(a.ngay,'dd/mm/yy') between to_date('" + tu.Text + "','dd/mm/yy') and to_date('" + den.Text + "','dd/mm/yy')";
                        //bhyt
                        sql += " union all ";
                        sql += "select distinct 2 as loai,'bhytkb' as ll,'bhytthuoc' as ct,0 as id,to_char(a.maphu)||to_char(b.makho)||'/'||to_char(a.ngay,'ddmm') as sophieu,";
                        sql += "to_char(a.ngay,'dd/mm/yyyy') as ngay,";
                        sql += "e.ten as nguon,d.ten as kho,'' as khoa,a.maphu as makhoa,c.doituong as ghichu,";
                        sql += "e.stk,nvl(e.ketoan,1) as tcnkp,d.useridkt,b.makho,b.ketoan";
                        sql += " from " + d.user + mmyy + ".bhytkb a," + d.user + mmyy + ".bhytthuoc b," + d.user + ".d_doituong c,";
                        sql += d.user + ".d_dmkho d," + d.user + ".d_dmnguon e," + user + ".a_dmtk f";
                        sql += " where a.id=b.id and a.maphu=c.madoituong and b.makho=d.id ";
                        sql += " and a.nhom=" + int.Parse(nhom.SelectedValue.ToString());
                        sql += " and e.stk=f.id(+) ";
                        sql += " and to_date(a.ngay,'dd/mm/yy') between to_date('" + tu.Text + "','dd/mm/yy') and to_date('" + den.Text + "','dd/mm/yy')";
                        //ngoai tru
                        sql += " union all ";
                        sql += "select distinct 1 as loai,'d_ngtrull' as ll,'d_ngtruct' as ct,0 as id,a.mabn||to_char(b.makho)||'/'||to_char(a.ngay,'ddmm') as sophieu,";
                        sql += "to_char(a.ngay,'dd/mm/yyyy') as ngay,";
                        sql += "e.ten as nguon,d.ten as kho,'' as khoa,a.loai as makhoa,c.ten as ghichu,";
                        sql += "e.stk,nvl(e.ketoan,1) as tcnkp,d.useridkt,b.makho,b.ketoan";
                        sql += " from " + d.user + mmyy + ".d_ngtrull a," + d.user + mmyy + ".d_ngtruct b," + d.user + ".d_dmloaint c,";
                        sql += d.user + ".d_dmkho d," + d.user + ".d_dmnguon e," + user + ".a_dmtk f";
                        sql += " where a.id=b.id and a.loai=c.id(+) and b.makho=d.id ";
                        sql += " and a.nhom=" + int.Parse(nhom.SelectedValue.ToString());
                        sql += " and e.stk=f.id(+) ";
                        sql += " and to_date(a.ngay,'dd/mm/yy') between to_date('" + tu.Text + "','dd/mm/yy') and to_date('" + den.Text + "','dd/mm/yy')";
                        //xuatsd
                        sql += " union all ";
                        sql += "select distinct 0 as loai,'d_xuatsdll' as ll,'d_thucxuat' as ct,0 as id,to_char(a.makhoa)||to_char(b.makho)||'/'||to_char(a.ngay,'ddmm') as sophieu,";
                        sql += "to_char(a.ngay,'dd/mm/yyyy') as ngay,";
                        sql += "e.ten as nguon,d.ten as kho,'' as khoa,a.makhoa,c.ten as ghichu,";
                        sql += "e.stk,nvl(e.ketoan,1) as tcnkp,d.useridkt,b.makho,b.ketoan";
                        sql += " from " + d.user + mmyy + ".d_xuatsdll a," + d.user + mmyy + ".d_thucxuat b," + d.user + ".d_duockp c,";
                        sql += d.user + ".d_dmkho d," + d.user + ".d_dmnguon e," + user + ".a_dmtk f";
                        sql += " where a.id=b.id and a.makhoa=c.id(+) and b.makho=d.id ";
                        sql += " and a.nhom=" + int.Parse(nhom.SelectedValue.ToString());
                        sql += " and e.stk=f.id(+) ";
                        sql += " and to_date(a.ngay,'dd/mm/yy') between to_date('" + tu.Text + "','dd/mm/yy') and to_date('" + den.Text + "','dd/mm/yy')";

                        foreach (DataRow r in a.get_data(sql).Tables[0].Select("true", "loai,sophieu,ngay,ghichu"))
                            updrec_congno(ds.Tables[0], mmyy, int.Parse(r["loai"].ToString()), r["ll"].ToString(),
                                r["ct"].ToString(), long.Parse(r["id"].ToString()), r["sophieu"].ToString(),
                                r["ngay"].ToString(), r["nguon"].ToString(), r["kho"].ToString(), r["khoa"].ToString(),
                                int.Parse(r["makhoa"].ToString()), r["ghichu"].ToString(), long.Parse(r["stk"].ToString()),
                                int.Parse(r["tcnkp"].ToString()), long.Parse(r["ketoan"].ToString()),
                                int.Parse(r["makho"].ToString()), (int.Parse(r["useridkt"].ToString()) == 0) ? iUserid : int.Parse(r["useridkt"].ToString()));
					}
				}
			}
			dataGrid1.DataSource=ds.Tables[0];
			CurrencyManager cm = (CurrencyManager)BindingContext[dataGrid1.DataSource,dataGrid1.DataMember]; 
			DataView dv = (DataView) cm.List; 
			dv.AllowNew = false; 
			try
			{				
				int i=dataGrid1.CurrentCell.RowNumber;
				load_ct(dataGrid1[i,5].ToString(),int.Parse(dataGrid1[i,1].ToString()),int.Parse(dataGrid1[i,2].ToString()),int.Parse(dataGrid1[i,3].ToString()),int.Parse(dataGrid1[i,4].ToString()),long.Parse(dataGrid1[i,6].ToString()),dataGrid1[i,10].ToString());
			}
			catch{}
		}

        //public void updrec_congno(DataTable dt,string mmyy,int loai,string tablell,string tablect,long id,
        //    string sophieu,string ngaysp,string nguon,string kho,string khoa,int makhoa,string ghichu,
        //    long tkno,int tcnkp,long ketoan,int makho,int manguon,int userid)
        //{
        //    string exp="id="+id+" and loai="+loai+" and mmyy='"+mmyy+"' and ngaysp='"+ngaysp+"' and makhoa="+makhoa;
        //    exp+=" and makho="+makho+" and manguon="+manguon;
        //    DataRow r = a.getrowbyid (dt,exp); 
        //    if ( r == null )
        //    {
        //        DataRow nrow = dt.NewRow ( ) ;
        //        nrow["mmyy"]=mmyy;
        //        nrow["id"] = id;
        //        nrow["loai"]=loai;
        //        nrow["sophieu"] = sophieu;
        //        nrow["ngaysp"] = ngaysp;
        //        nrow["tablell"] = tablell;
        //        nrow["tablect"] = tablect;
        //        nrow["nguon"]=nguon;
        //        nrow["kho"] = kho;
        //        nrow["khoa"] = khoa;
        //        nrow["makhoa"] = makhoa;
        //        nrow["tknosave"]=nrow["tkno"] = (tcnkp==0 && bStkhangnam)?iTknonamtruoc:tkno;
        //        nrow["tcnkp"]=tcnkp;
        //        nrow["ghichu"]=ghichu;
        //        nrow["sotien"]=ketoan;
        //        nrow["makho"]=makho;
        //        nrow["manguon"]=manguon;
        //        nrow["userid"]=userid;
        //        nrow["chon"]=ketoan!=0;
        //        DataRow r1=a.getrowbyid(dttk,"id="+int.Parse(nrow["tkno"].ToString()));
        //        nrow["ttknosave"]=nrow["ttkno"]=(r1!=null)?r1["stk"].ToString():"";
        //        if (ketoan!=0)
        //        {
        //            foreach(DataRow r2 in a.get_data("select * from a_impxuat where mmyy='"+mmyy+"' and id="+id+" and loai="+loai+" and sophieu='"+sophieu+"' and to_char(ngay,'dd/mm/yyyy')='"+ngaysp+"' and tablell='"+tablell+"' and tablect='"+tablect+"' and makhoa="+makhoa+" and makho="+makho+" and manguon="+manguon).Tables[0].Rows)
        //            {
        //                nrow["tkno"]=r2["tkno"].ToString();
        //                nrow["ttkno"]=nrow["ttknosave"]=r2["ttkno"].ToString();
        //            }
        //        }
        //        dt.Rows.Add ( nrow ) ;
        //    }
        //}
        public void updrec_congno(DataTable dt, string mmyy, int loai, string tablell, string tablect, long id,
            string sophieu, string ngaysp, string nguon, string kho, string khoa, int makhoa, string ghichu,
            long tkno, int tcnkp, long ketoan, int makho, int userid)
        {
            string exp = "id=" + id + " and loai=" + loai + " and mmyy='" + mmyy + "' and ngaysp='" + ngaysp + "' and makhoa=" + makhoa;
            exp += " and makho=" + makho;
            DataRow r = a.getrowbyid(dt, exp);
            if (r == null)
            {
                DataRow nrow = dt.NewRow();
                nrow["mmyy"] = mmyy;
                nrow["id"] = id;
                nrow["loai"] = loai;
                nrow["sophieu"] = sophieu;
                nrow["ngaysp"] = ngaysp;
                nrow["tablell"] = tablell;
                nrow["tablect"] = tablect;
                nrow["nguon"] = nguon;
                nrow["kho"] = kho;
                nrow["khoa"] = khoa;
                nrow["makhoa"] = makhoa;
                nrow["tknosave"] = nrow["tkno"] = (tcnkp == 0 && bStkhangnam) ? iTknonamtruoc : tkno;
                nrow["tcnkp"] = tcnkp;
                nrow["ghichu"] = ghichu;
                nrow["sotien"] = ketoan;
                nrow["makho"] = makho;
                nrow["userid"] = userid;
                nrow["chon"] = ketoan != 0;
                DataRow r1 = a.getrowbyid(dttk, "id=" + int.Parse(nrow["tkno"].ToString()));
                nrow["ttknosave"] = nrow["ttkno"] = (r1 != null) ? r1["stk"].ToString() : "";
                if (ketoan != 0)
                {
                    foreach (DataRow r2 in a.get_data("select * from a_impxuat where mmyy='" + mmyy + "' and id=" + id + " and loai=" + loai + " and sophieu='" + sophieu + "' and to_char(ngay,'dd/mm/yyyy')='" + ngaysp + "' and tablell='" + tablell + "' and tablect='" + tablect + "' and makhoa=" + makhoa + " and makho=" + makho).Tables[0].Rows)
                    {
                        nrow["tkno"] = r2["tkno"].ToString();
                        nrow["ttkno"] = nrow["ttknosave"] = r2["ttkno"].ToString();
                    }
                }
                dt.Rows.Add(nrow);
            }
        }

		private void AddGridTableStyle()
		{
			DataGridTableStyle ts =new DataGridTableStyle();
			ts.MappingName = ds.Tables[0].TableName;
			ts.AlternatingBackColor = Color.Beige;
			ts.BackColor = Color.GhostWhite;
			ts.ForeColor = Color.MidnightBlue;
			ts.GridLineColor = Color.RoyalBlue;
			ts.HeaderBackColor = Color.MidnightBlue;
			ts.HeaderForeColor = Color.Lavender;
			ts.SelectionBackColor = Color.FromArgb(0,255,255);
			ts.SelectionForeColor = Color.PaleGreen;
			ts.RowHeaderWidth=5;
					
			FormattableBooleanColumn discontinuedCol = new FormattableBooleanColumn();
			discontinuedCol.MappingName = "chon";
			discontinuedCol.HeaderText = "Chọn";
			discontinuedCol.Width = 30;
			discontinuedCol.AllowNull = false;

			discontinuedCol.SetCellFormat += new FormatCellEventHandler(SetCellFormat);
			discontinuedCol.BoolValueChanged += new BoolValueChangedEventHandler(BoolValueChanged);
			ts.GridColumnStyles.Add(discontinuedCol);
			dataGrid1.TableStyles.Add(ts);

			FormattableTextBoxColumn TextCol = new FormattableTextBoxColumn();
			TextCol.MappingName = "loai";
			TextCol.HeaderText = "";
			TextCol.Width =0;
			ts.GridColumnStyles.Add(TextCol);
			dataGrid1.TableStyles.Add(ts);

			TextCol = new FormattableTextBoxColumn();
			TextCol.MappingName = "makho";
			TextCol.HeaderText = "";
			TextCol.Width =0;
			ts.GridColumnStyles.Add(TextCol);
			dataGrid1.TableStyles.Add(ts);

			TextCol = new FormattableTextBoxColumn();
			TextCol.MappingName = "manguon";
			TextCol.HeaderText = "";
			TextCol.Width =0;
			ts.GridColumnStyles.Add(TextCol);
			dataGrid1.TableStyles.Add(ts);

			TextCol = new FormattableTextBoxColumn();
			TextCol.MappingName = "makhoa";
			TextCol.HeaderText = "";
			TextCol.Width =0;
			ts.GridColumnStyles.Add(TextCol);
			dataGrid1.TableStyles.Add(ts);

			TextCol = new FormattableTextBoxColumn();
			TextCol.MappingName = "mmyy";
			TextCol.HeaderText = "";
			TextCol.Width =0;
			ts.GridColumnStyles.Add(TextCol);
			dataGrid1.TableStyles.Add(ts);

			TextCol = new FormattableTextBoxColumn();
			TextCol.MappingName = "id";
			TextCol.HeaderText = "";
			TextCol.Width =0;
			ts.GridColumnStyles.Add(TextCol);
			dataGrid1.TableStyles.Add(ts);

			TextCol = new FormattableTextBoxColumn();
			TextCol.MappingName = "nguon";
			TextCol.HeaderText = "Nguồn";
			TextCol.Width =150;
			TextCol.ReadOnly=true;
			TextCol.SetCellFormat += new FormatCellEventHandler(SetCellFormat);
			ts.GridColumnStyles.Add(TextCol);
			dataGrid1.TableStyles.Add(ts);

			TextCol = new FormattableTextBoxColumn();
			TextCol.MappingName = "kho";
			TextCol.HeaderText = "Kho";
			TextCol.Width =210;
			TextCol.ReadOnly=true;
			TextCol.SetCellFormat += new FormatCellEventHandler(SetCellFormat);
			ts.GridColumnStyles.Add(TextCol);
			dataGrid1.TableStyles.Add(ts);

			TextCol = new FormattableTextBoxColumn();
			TextCol.MappingName = "sophieu";
			TextCol.HeaderText = "Số phiếu";
			TextCol.Width =100;
			TextCol.ReadOnly=true;
			TextCol.SetCellFormat += new FormatCellEventHandler(SetCellFormat);
			ts.GridColumnStyles.Add(TextCol);
			dataGrid1.TableStyles.Add(ts);

			TextCol=new FormattableTextBoxColumn();
			TextCol.MappingName = "ngaysp";
			TextCol.HeaderText = "Ngày";
			TextCol.Width = 65;
			TextCol.ReadOnly=true;
			TextCol.SetCellFormat += new FormatCellEventHandler(SetCellFormat);
			ts.GridColumnStyles.Add(TextCol);
			dataGrid1.TableStyles.Add(ts);

			TextCol=new FormattableTextBoxColumn();
			TextCol.MappingName = "khoa";
			TextCol.HeaderText = "";
			TextCol.Width = 0;
			TextCol.ReadOnly=true;
			TextCol.SetCellFormat += new FormatCellEventHandler(SetCellFormat);
			ts.GridColumnStyles.Add(TextCol);
			dataGrid1.TableStyles.Add(ts);

			TextCol=new FormattableTextBoxColumn();
			TextCol.MappingName = "ttkno";
			TextCol.HeaderText = "STK Nợ";
			TextCol.Width =80;
			TextCol.ReadOnly=false;
			TextCol.SetCellFormat += new FormatCellEventHandler(SetCellFormat);
			ts.GridColumnStyles.Add(TextCol);
			dataGrid1.TableStyles.Add(ts);

			TextCol=new FormattableTextBoxColumn();
			TextCol.MappingName = "ghichu";
			TextCol.HeaderText = "Diễn giải";
			TextCol.Width =dataGrid1.Width-(35+30+100+60+65+150+100+50+80);
			TextCol.ReadOnly=true;
			TextCol.SetCellFormat += new FormatCellEventHandler(SetCellFormat);
			ts.GridColumnStyles.Add(TextCol);
			dataGrid1.TableStyles.Add(ts);

			TextCol=new FormattableTextBoxColumn();
			TextCol.MappingName = "sotien";
			TextCol.HeaderText = "";
			TextCol.Width =0;
			ts.GridColumnStyles.Add(TextCol);
			dataGrid1.TableStyles.Add(ts);
		}
	
		private void SetCellFormat(object sender, DataGridFormatCellEventArgs e)
		{
			try
			{
				bool discontinued = (bool) ((e.Column != 0) ? this.dataGrid1[e.Row, 0] : e.CurrentCellValue);
				if(e.Column > 0 && (bool)(this.dataGrid1[e.Row, 0]))//discontinued)
				{
					e.ForeBrush = this.disabledTextBrush;
				}
				else if(e.Column > 0 && e.Row == this.dataGrid1.CurrentRowIndex)
				{
					e.BackBrush = this.currentRowBackBrush;
					e.TextFont = this.currentRowFont;
				}
				if (decimal.Parse(dataGrid1[e.Row,14].ToString())!=0) e.ForeBrush=new SolidBrush(Color.Orange);
			}
			catch{}
		}

		private void BoolValueChanged(object sender, BoolValueChangedEventArgs e)
		{
			this.dataGrid1.EndEdit(this.dataGrid1.TableStyles[0].GridColumnStyles["Discontinued"],e.Row, false);
			RefreshRow(e.Row);
			this.dataGrid1.BeginEdit(this.dataGrid1.TableStyles[0].GridColumnStyles["Discontinued"],e.Row);
		}
		private void RefreshRow(int row)
		{
			Rectangle rect = this.dataGrid1.GetCellBounds(row, 0);
			rect = new Rectangle(rect.Right, rect.Top, this.dataGrid1.Width, rect.Height);
			this.dataGrid1.Invalidate(rect);
		}

		private void dataGrid1_CurrentCellChanged(object sender, System.EventArgs e)
		{
			if((bool)this.dataGrid1[this.dataGrid1.CurrentRowIndex, checkCol])
				this.dataGrid1.CurrentCell = new DataGridCell(this.dataGrid1.CurrentRowIndex, checkCol);
			afterCurrentCellChanged = true;
			try
			{
				int i=dataGrid1.CurrentCell.RowNumber;
				load_ct(dataGrid1[i,5].ToString(),int.Parse(dataGrid1[i,1].ToString()),int.Parse(dataGrid1[i,2].ToString()),int.Parse(dataGrid1[i,3].ToString()),int.Parse(dataGrid1[i,4].ToString()),long.Parse(dataGrid1[i,6].ToString()),dataGrid1[i,10].ToString());
			}
			catch{}
		}

		private void dataGrid1_Click(object sender, System.EventArgs e)
		{
			Point pt = this.dataGrid1.PointToClient(Control.MousePosition);
			DataGrid.HitTestInfo hti = this.dataGrid1.HitTest(pt);
			BindingManagerBase bmb = this.BindingContext[this.dataGrid1.DataSource, this.dataGrid1.DataMember];
			if(afterCurrentCellChanged && hti.Row < bmb.Count 
				&& hti.Type == DataGrid.HitTestType.Cell 
				&&  hti.Column == checkCol )
			{	
				this.dataGrid1[hti.Row, checkCol] = !(bool)this.dataGrid1[hti.Row, checkCol];
				RefreshRow(hti.Row);
			}
			afterCurrentCellChanged = false;
		}

		private void tu_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
		{
			if (e.KeyCode==Keys.Enter) SendKeys.Send("{Tab}");
		}

		private void sophieu_TextChanged(object sender, System.EventArgs e)
		{
			if (this.ActiveControl==sophieu) ref_grid();
		}

		private void madv_TextChanged(object sender, System.EventArgs e)
		{
			if (this.ActiveControl==madv) ref_grid();
		}

		private void ref_grid()
		{
			CurrencyManager cm= (CurrencyManager)BindingContext[dataGrid1.DataSource];
			DataView dv=(DataView)cm.List;
			sql="";
			if (sophieu.Text!="")
			{
				if (sql!="") sql+=" and ";
				sql+=" sophieu like '%"+sophieu.Text+"%'";
			}
			if (madv.Text!="")
			{
				if (sql!="") sql+=" and ";
				sql+=" ghichu like '%"+madv.Text+"%'";
			}
			dv.RowFilter=sql;
		}

		private void butTonghop_Click(object sender, System.EventArgs e)
		{
			format_sotien=a.format_sotien(int.Parse(nhom.SelectedValue.ToString()));
			load_grid();
		}

		private bool kiemtra()
		{
			if (a.bKhoaso(s_mmyy))
			{
				MessageBox.Show("Số liệu tháng "+s_mmyy.Substring(0,2)+" năm 20"+s_mmyy.Substring(2)+" đã khóa sổ !",a.Msg);
				tu.Focus();
				return false;
			}
			string s="",xxx,s1="";
			DataRow r1;
			ds.AcceptChanges();
			if (chkNo.Checked && ds.Tables[0].Select("chon=true and sotien=0").Length>1)
			{
				MessageBox.Show("Tài khoản nợ chi tiết mặt hàng mổi lần chỉ thu nhập một chứng từ !",a.Msg);
				dataGrid1.Focus();
				return false;
			}
			foreach(DataRow r in ds.Tables[0].Select("chon=true and sotien=0"))
			{
				if (r["ttkno"].ToString()!=r["ttknosave"].ToString())
				{
					r1=a.getrowbyid(dttk,"stk='"+r["ttkno"].ToString()+"'");
					if (r1!=null)
					{
						r["tkno"]=r1["id"].ToString();
						a.upd_impxuat(r["mmyy"].ToString(),long.Parse(r["id"].ToString()),int.Parse(r["loai"].ToString()),r["sophieu"].ToString(),r["ngaysp"].ToString(),r["tablell"].ToString(),r["tablect"].ToString(),int.Parse(r["makhoa"].ToString()),int.Parse(r["makho"].ToString()),int.Parse(r["manguon"].ToString()),int.Parse(r["tcnkp"].ToString()),long.Parse(r1["id"].ToString()),long.Parse(r["tknosave"].ToString()),r1["stk"].ToString());
					}
					else s1+=r["ttkno"].ToString()+"\n";
				}
				xxx=d.user+r["mmyy"].ToString();
				if (r["loai"].ToString()=="3")
				{
					sql="select f.id,b.ma,trim(b.ten)||' '||trim(b.hamluong) as ten,b.dang ";
					sql+=" from "+xxx+".d_xuatct a,"+user+".d_dmbd b,"+d.user+".d_dmnhomkt e,"+user+".a_dmtk f";
					sql+=" where a.mabd=b.id and b.sotk=e.id(+) and e.ma=f.stk(+) and a.id="+long.Parse(r["id"].ToString());
					sql+=" and a.manguon="+int.Parse(r["manguon"].ToString());
					sql+=" and (f.id is null or b.sotk is null)";
				}
				else if (r["loai"].ToString()=="2")
				{
					sql="select f.id,b.ma,trim(b.ten)||' '||trim(b.hamluong) as ten,b.dang ";
					sql+=" from "+xxx+".bhytkb ll,"+xxx+".bhytthuoc a,"+d.user+".d_dmbd b,"+d.user+".d_dmnhomkt e,"+user+".a_dmtk f";
					sql+=" where ll.id=a.id and a.mabd=b.id and b.sotk=e.id(+) and e.ma=f.stk(+) ";
					sql+=" and to_char(ll.ngay,'dd/mm/yyyy')='"+r["ngaysp"].ToString()+"'";
					sql+=" and ll.maphu="+int.Parse(r["makhoa"].ToString())+" and a.makho="+int.Parse(r["makho"].ToString());
					sql+=" and a.manguon="+int.Parse(r["manguon"].ToString());
					sql+=" and (f.id is null or b.sotk is null)";
				}
				else if (r["loai"].ToString()=="1")
				{
					sql="select f.id,b.ma,trim(b.ten)||' '||trim(b.hamluong) as ten,b.dang ";
					sql+=" from "+xxx+".d_ngtrull ll,"+xxx+".d_ngtruct a,"+d.user+".d_dmbd b,"+d.user+".d_dmnhomkt e,"+user+".a_dmtk f";
					sql+=" where ll.id=a.id and a.mabd=b.id and b.sotk=e.id(+) and e.ma=f.stk(+) ";
					sql+=" and to_char(ll.ngay,'dd/mm/yyyy')='"+r["ngaysp"].ToString()+"'";
					sql+=" and ll.loai="+int.Parse(r["makhoa"].ToString())+" and a.makho="+int.Parse(r["makho"].ToString());
					sql+=" and a.manguon="+int.Parse(r["manguon"].ToString());
					sql+=" and (f.id is null or b.sotk is null)";
				}
				else
				{
					sql="select f.id,b.ma,trim(b.ten)||' '||trim(b.hamluong) as ten,b.dang ";
					sql+=" from "+xxx+".d_xuatsdll ll,"+xxx+".d_thucxuat a,"+d.user+".d_dmbd b,"+d.user+".d_dmnhomkt e,"+user+".a_dmtk f";
					sql+=" where ll.id=a.id and a.mabd=b.id and b.sotk=e.id(+) and e.ma=f.stk(+) ";
					sql+=" and to_char(ll.ngay,'dd/mm/yyyy')='"+r["ngaysp"].ToString()+"'";
					sql+=" and ll.makhoa="+int.Parse(r["makhoa"].ToString())+" and a.makho="+int.Parse(r["makho"].ToString());
					sql+=" and a.manguon="+int.Parse(r["manguon"].ToString());
					sql+=" and (f.id is null or b.sotk is null)";
				}
				foreach(DataRow r2 in a.get_data(sql).Tables[0].Rows)
					if (s.IndexOf(r2["ten"].ToString().Trim()+" "+r2["dang"].ToString().Trim())==-1) s+=r2["ten"].ToString().Trim()+" "+r2["dang"].ToString().Trim()+"\n";
			}
			ds.AcceptChanges();
			if (s!="")
			{
				MessageBox.Show("Những mặt hàng sau khai báo tài khoản không hợp lệ :\n"+s,a.Msg);
				tu.Focus();
				return false;
			}
			if (s1!="")
			{
				MessageBox.Show("Những tài khoản nợ sau không hợp lệ :\n"+s1,a.Msg);
				tu.Focus();
				return false;
			}
			if (bStkhangnam)
			{
				string stk="";
				foreach(DataRow r in ds.Tables[0].Rows)
				{
					xxx=d.user+r["mmyy"].ToString();
					if (r["chon"].ToString().Trim().ToLower()=="true" && decimal.Parse(r["sotien"].ToString())==0)
					{
						if (r["loai"].ToString()=="3")
						{
							sql="select f.id,h.stk,e.ma,e.ten";
							sql+=" from "+xxx+".d_xuatll ll,"+xxx+".d_xuatct a,"+d.user+".d_dmbd b,";
							sql+=d.user+".d_dmnhomkt e,"+user+".a_dmtk f,"+d.user+".d_dmnguon h";
							sql+=" where ll.id=a.id and a.manguon=h.id and a.mabd=b.id ";
							sql+=" and b.sotk=e.id and e.ma=f.stk and ll.id="+long.Parse(r["id"].ToString());
							sql+=" and a.manguon="+int.Parse(r["manguon"].ToString());
							sql+=" group by f.id,h.stk,e.ma,e.ten order by f.id,h.stk,e.ma,e.ten";
						}
						else if (r["loai"].ToString()=="2")
						{
							sql="select f.id,h.stk,e.ma,e.ten";
							sql+=" from "+xxx+".bhytkb ll,"+xxx+".bhytthuoc a,"+d.user+".d_dmbd b,";
							sql+=d.user+".d_dmnhomkt e,"+user+".a_dmtk f,"+d.user+".d_dmnguon h";
							sql+=" where ll.id=a.id and a.manguon=h.id and a.mabd=b.id ";
							sql+=" and b.sotk=e.id and e.ma=f.stk ";
							sql+=" and to_char(ll.ngay,'dd/mm/yyyy')='"+r["ngaysp"].ToString()+"'";
							sql+=" and ll.maphu="+long.Parse(r["makhoa"].ToString());
							sql+=" and a.makho="+long.Parse(r["makho"].ToString());
							sql+=" and a.manguon="+long.Parse(r["manguon"].ToString());
							sql+=" group by f.id,h.stk,e.ma,e.ten order by f.id,h.stk,e.ma,e.ten";
						}
						else if (r["loai"].ToString()=="1")
						{
							sql="select f.id,h.stk,e.ma,e.ten";
							sql+=" from "+xxx+".d_ngtrull ll,"+xxx+".d_ngtruct a,"+d.user+".d_dmbd b,";
							sql+=d.user+".d_dmnhomkt e,"+user+".a_dmtk f,"+d.user+".d_dmnguon h";
							sql+=" where ll.id=a.id and a.manguon=h.id and a.mabd=b.id ";
							sql+=" and b.sotk=e.id and e.ma=f.stk ";
							sql+=" and to_char(ll.ngay,'dd/mm/yyyy')='"+r["ngaysp"].ToString()+"'";
							sql+=" and ll.loai="+long.Parse(r["makhoa"].ToString());
							sql+=" and a.makho="+long.Parse(r["makho"].ToString());
							sql+=" and a.manguon="+long.Parse(r["manguon"].ToString());
							sql+=" group by f.id,h.stk,e.ma,e.ten order by f.id,h.stk,e.ma,e.ten";
						}
						else
						{
							sql="select f.id,h.stk,e.ma,e.ten";
							sql+=" from "+xxx+".d_xuatsdll ll,"+xxx+".d_thucxuat a,"+d.user+".d_dmbd b,";
							sql+=d.user+".d_dmnhomkt e,"+user+".a_dmtk f,"+d.user+".d_dmnguon h";
							sql+=" where ll.id=a.id and a.manguon=h.id and a.mabd=b.id ";
							sql+=" and b.sotk=e.id and e.ma=f.stk ";
							sql+=" and to_char(ll.ngay,'dd/mm/yyyy')='"+r["ngaysp"].ToString()+"'";
							sql+=" and ll.makhoa="+long.Parse(r["makhoa"].ToString());
							sql+=" and a.makho="+long.Parse(r["makho"].ToString());
							sql+=" and a.manguon="+long.Parse(r["manguon"].ToString());
							sql+=" group by f.id,h.stk,e.ma,e.ten order by f.id,h.stk,e.ma,e.ten";
						}
						foreach(DataRow r2 in a.get_data(sql).Tables[0].Rows)
						{
							stk=r2["ma"].ToString();
							if (r2["stk"].ToString()=="1") stk=stk.Substring(0,stk.Length-1)+"2";
							r1=a.getrowbyid(dttk,"stk='"+stk+"'");
							if (r1==null) s+=stk+"\n";
						}
					}
				}
				if (s!="")
				{
					MessageBox.Show("Số tài khoản nợ sau không hợp lệ :\n"+s,a.Msg);
					tu.Focus();
					return false;
				}
			}
			if (chkNo.Checked)
			{
				s1="";
				dsct.AcceptChanges();
				foreach(DataRow r in dsct.Tables[0].Rows)
				{
					r1=a.getrowbyid(dttk,"stk='"+r["ttkno"].ToString()+"'");
					if (r1!=null)
					{
						r["tkno"]=r1["id"].ToString();
						if (r["ttkno"].ToString()!=r["ttknosave"].ToString())
							a.upd_impxuatct(r["mmyy"].ToString(),long.Parse(r["idct"].ToString()),int.Parse(r["loai"].ToString()),r["ngay"].ToString(),r["ma"].ToString(),r["ttkno"].ToString());
					}
					else s1+=r["ttkno"].ToString()+"\n";
				}
				if (s1!="")
				{
					MessageBox.Show("Số tài khoản nợ sau không hợp lệ :\n"+s1,a.Msg);
					dataGrid2.Focus();
					return false;
				}
				dsct.AcceptChanges();
			}
			iHoatdong=int.Parse(c700.SelectedValue.ToString());
			iChuong=int.Parse(c702.SelectedValue.ToString());
			iNghiepvu=int.Parse(c703.SelectedValue.ToString());
			iLoaibk=int.Parse(c705.SelectedValue.ToString());
			iLk=int.Parse(c706.SelectedValue.ToString());
			iCapphat=int.Parse(c707.SelectedValue.ToString());
			iNhom=int.Parse(c710.SelectedValue.ToString());
			return true;
		}

		private void butLuu_Click(object sender, System.EventArgs e)
		{
			CurrencyManager cm= (CurrencyManager)BindingContext[dataGrid1.DataSource];
			DataView dv=(DataView)cm.List;
			dv.RowFilter="";
			if (!kiemtra()) return;
			long idct=0,idctct=0,tknoa;
			int stt=1;
			string xxx,ttk,id="";
			decimal st=0;
			bool bUpdate=false;
			DataRow r1,r3;
			DataRow [] dr;
			DataTable tmp=new DataTable();
			foreach(DataRow r in ds.Tables[0].Rows)
			{
				id="";
				if (r["chon"].ToString().Trim().ToLower()=="true" && decimal.Parse(r["sotien"].ToString())==0)
				{
					idct=a.getIdct();xxx=d.user+r["mmyy"].ToString();
					a.updCt(s_mmyy,idct,iNhom,"",iChuong,iChucnang,iHoatdong,iLctug,r["sophieu"].ToString(),
						r["ngaysp"].ToString(),s_ngay,r["ghichu"].ToString(),long.Parse(r["tkno"].ToString()),
						0,-1,0,0,0,s_mmyy.Substring(0,2),iNghiepvu,iLoaibk,int.Parse(r["tcnkp"].ToString()),0,"",0,int.Parse(r["userid"].ToString()));
					a.updCtk(s_mmyy,idct,r["ghichu"].ToString(),"");
					st=0;stt=1;
					if (!chkNo.Checked)
					{
						if (r["loai"].ToString()=="3")
						{
							sql="select f.id,h.stk,e.ma,e.ten,sum(a.soluong*t.giamua) as sotien ";
							sql+=" from "+xxx+".d_xuatll ll,"+xxx+".d_xuatct a,"+d.user+".d_dmbd b,";
							sql+=d.user+".d_dmnhomkt e,"+user+".a_dmtk f,"+d.user+".d_dmnguon h,"+xxx+".d_theodoi t";
							sql+=" where ll.id=a.id and a.sttt=t.id and a.manguon=h.id and a.mabd=b.id ";
							sql+=" and b.sotk=e.id and e.ma=f.stk and ll.id="+long.Parse(r["id"].ToString());
							sql+=" and a.manguon="+int.Parse(r["manguon"].ToString());
							sql+=" group by f.id,h.stk,e.ma,e.ten order by f.id,h.stk,e.ma,e.ten";
						}
						else if (r["loai"].ToString()=="2")
						{
							sql="select f.id,h.stk,e.ma,e.ten,sum(a.soluong*t.giamua) as sotien ";
							sql+=" from "+xxx+".bhytkb ll,"+xxx+".bhytthuoc a,"+d.user+".d_dmbd b,";
							sql+=d.user+".d_dmnhomkt e,"+user+".a_dmtk f,"+d.user+".d_dmnguon h,"+xxx+".d_theodoi t";
							sql+=" where ll.id=a.id and a.sttt=t.id and a.manguon=h.id and a.mabd=b.id ";
							sql+=" and b.sotk=e.id and e.ma=f.stk and to_char(ll.ngay,'dd/mm/yyyy')='"+r["ngaysp"].ToString()+"'";
							sql+=" and ll.maphu="+int.Parse(r["makhoa"].ToString());
							sql+=" and a.makho="+int.Parse(r["makho"].ToString());
							sql+=" and a.manguon="+int.Parse(r["manguon"].ToString());
							sql+=" group by f.id,h.stk,e.ma,e.ten order by f.id,h.stk,e.ma,e.ten";
						}
						else if (r["loai"].ToString()=="1")
						{
							sql="select f.id,h.stk,e.ma,e.ten,sum(a.soluong*t.giamua) as sotien ";
							sql+=" from "+xxx+".d_ngtrull ll,"+xxx+".d_ngtruct a,"+d.user+".d_dmbd b,";
							sql+=d.user+".d_dmnhomkt e,"+user+".a_dmtk f,"+d.user+".d_dmnguon h,"+xxx+".d_theodoi t";
							sql+=" where ll.id=a.id and a.sttt=t.id and a.manguon=h.id and a.mabd=b.id ";
							sql+=" and b.sotk=e.id and e.ma=f.stk and to_char(ll.ngay,'dd/mm/yyyy')='"+r["ngaysp"].ToString()+"'";
							sql+=" and ll.loai="+int.Parse(r["makhoa"].ToString());
							sql+=" and a.makho="+int.Parse(r["makho"].ToString());
							sql+=" and a.manguon="+int.Parse(r["manguon"].ToString());
							sql+=" group by f.id,h.stk,e.ma,e.ten order by f.id,h.stk,e.ma,e.ten";
						}
						else
						{
							sql="select f.id,h.stk,e.ma,e.ten,sum(a.soluong*t.giamua) as sotien ";
							sql+=" from "+xxx+".d_xuatsdll ll,"+xxx+".d_thucxuat a,"+d.user+".d_dmbd b,";
							sql+=d.user+".d_dmnhomkt e,"+user+".a_dmtk f,"+d.user+".d_dmnguon h,"+xxx+".d_theodoi t";
							sql+=" where ll.id=a.id and a.sttt=t.id and a.manguon=h.id and a.mabd=b.id ";
							sql+=" and b.sotk=e.id and e.ma=f.stk and to_char(ll.ngay,'dd/mm/yyyy')='"+r["ngaysp"].ToString()+"'";
							sql+=" and ll.loai<>3 and ll.makhoa="+int.Parse(r["makhoa"].ToString());
							sql+=" and a.makho="+int.Parse(r["makho"].ToString());
							sql+=" and a.manguon="+int.Parse(r["manguon"].ToString());
							sql+=" group by f.id,h.stk,e.ma,e.ten order by f.id,h.stk,e.ma,e.ten";
						}
						tmp=a.get_data(sql).Tables[0];
						if (r["loai"].ToString()=="0")
						{
							sql="select f.id,h.stk,e.ma,e.ten,sum(-1*a.soluong*t.giamua) as sotien ";
							sql+=" from "+xxx+".d_xuatsdll ll,"+xxx+".d_thucxuat a,"+d.user+".d_dmbd b,";
							sql+=d.user+".d_dmnhomkt e,"+user+".a_dmtk f,"+d.user+".d_dmnguon h,"+xxx+".d_theodoi t";
							sql+=" where ll.id=a.id and a.sttt=t.id and a.manguon=h.id and a.mabd=b.id ";
							sql+=" and b.sotk=e.id and e.ma=f.stk and to_char(ll.ngay,'dd/mm/yyyy')='"+r["ngaysp"].ToString()+"'";
							sql+=" and ll.loai=3 and ll.makhoa="+int.Parse(r["makhoa"].ToString());
							sql+=" and a.makho="+int.Parse(r["makho"].ToString());
							sql+=" and a.manguon="+int.Parse(r["manguon"].ToString());
							sql+=" group by f.id,h.stk,e.ma,e.ten order by f.id,h.stk,e.ma,e.ten";
							foreach(DataRow r2 in a.get_data(sql).Tables[0].Rows)
							{
								sql="id="+int.Parse(r2["id"].ToString());
								r1=a.getrowbyid(tmp,sql);
								if (r1==null)
								{
									r3=tmp.NewRow();
									r3["id"]=r2["id"].ToString();
									r3["stk"]=r2["stk"].ToString();
									r3["ma"]=r2["ma"].ToString();
									r3["ten"]=r2["ten"].ToString();
									r3["sotien"]=r2["sotien"].ToString();
									tmp.Rows.Add(r3);
								}
								else 
								{
									dr=tmp.Select(sql);
									if (dr.Length>0) dr[0]["sotien"]=decimal.Parse(dr[0]["sotien"].ToString())+Math.Round(decimal.Parse(r2["sotien"].ToString()),0);
								}
							}
						}
					}
					foreach(DataRow r2 in (chkNo.Checked)?dsct.Tables[0].Rows:tmp.Rows)
					{
						ttk=r2["ten"].ToString();st+=decimal.Parse(r2["sotien"].ToString());
						idctct=a.getIdctct();
						tknoa=(chkNo.Checked)?long.Parse(r2["tkno"].ToString()):long.Parse(r["tkno"].ToString());
						a.updCtct(s_mmyy,idctct,idct,stt++,iLk,ttk,tknoa,long.Parse(r2["id"].ToString()),
							(khoanmuc.SelectedIndex==-1)?0:long.Parse(khoanmuc.SelectedValue.ToString()),0,
							(khoanmuc2.SelectedIndex==-1)?0:long.Parse(khoanmuc2.SelectedValue.ToString()),0,
							(khoanmuc3.SelectedIndex==-1)?0:long.Parse(khoanmuc3.SelectedValue.ToString()),0,
							(khoanmuc4.SelectedIndex==-1)?0:long.Parse(khoanmuc4.SelectedValue.ToString()),0,0,0,
							Math.Round(decimal.Parse(r2["sotien"].ToString()),0),0,0,1,iTonghop,0,iCapphat,iLctug,"",
							r["ngaysp"].ToString(),iChuong,0,iNghiepvu,0,iHoatdong,int.Parse(r["userid"].ToString()));
						if (iTonghop==1)
						{
							a.updSodu("a_sd",a.insert,s_mmyy,iNhom,iChuong,0,iLk,iNghiepvu,0,
								tknoa,long.Parse(r2["id"].ToString()),(khoanmuc.SelectedIndex==-1)?0:long.Parse(khoanmuc.SelectedValue.ToString()),0,(khoanmuc2.SelectedIndex==-1)?0:long.Parse(khoanmuc2.SelectedValue.ToString()),0,(khoanmuc3.SelectedIndex==-1)?0:long.Parse(khoanmuc3.SelectedValue.ToString()),0,(khoanmuc4.SelectedIndex==-1)?0:long.Parse(khoanmuc4.SelectedValue.ToString()),0,0,0,iHoatdong,Math.Round(decimal.Parse(r2["sotien"].ToString()),0));
							a.updSodu("a_sdc",a.insert,s_mmyy,iNhom,iChuong,0,iLk,iNghiepvu,0,
								tknoa,long.Parse(r2["id"].ToString()),(khoanmuc.SelectedIndex==-1)?0:long.Parse(khoanmuc.SelectedValue.ToString()),0,(khoanmuc2.SelectedIndex==-1)?0:long.Parse(khoanmuc2.SelectedValue.ToString()),0,(khoanmuc3.SelectedIndex==-1)?0:long.Parse(khoanmuc3.SelectedValue.ToString()),0,(khoanmuc4.SelectedIndex==-1)?0:long.Parse(khoanmuc4.SelectedValue.ToString()),0,0,0,iHoatdong,Math.Round(decimal.Parse(r2["sotien"].ToString()),0));
							if (a.bChophanbo(tknoa,long.Parse(r2["id"].ToString())))
								a.updPhanbo("a_phanbochua",a.insert,idct,idctct,iLctug,r["sophieu"].ToString(),r["ngaysp"].ToString(),
									tknoa,long.Parse(r2["id"].ToString()),
									"",r2["ten"].ToString(),1,Math.Round(decimal.Parse(r2["sotien"].ToString()),0),iNghiepvu,s_mmyy,int.Parse(r["userid"].ToString()));
						}
					}
					
					a.execute_data("update "+user+".a_ct"+s_mmyy.Substring(2,2)+" set stien="+Math.Round(st,0)+" where id="+idct);
					if (r["loai"].ToString()=="3") a.execute_data("update "+d.user+r["mmyy"].ToString()+".d_xuatct set ketoan="+idct+" where id="+long.Parse(r["id"].ToString())+" and manguon="+int.Parse(r["manguon"].ToString()));
					else if (r["loai"].ToString()=="2")
					{
						id=getid(d.user+r["mmyy"].ToString()+".bhytkb",d.user+r["mmyy"].ToString()+".bhytthuoc",int.Parse(r["loai"].ToString()),r["ngaysp"].ToString(),int.Parse(r["makhoa"].ToString()),int.Parse(r["makho"].ToString()),int.Parse(r["manguon"].ToString()));
						if (id!="") a.execute_data("update "+d.user+r["mmyy"].ToString()+".bhytthuoc set ketoan="+idct+" where id in ("+id.Substring(0,id.Length-1)+") and manguon="+int.Parse(r["manguon"].ToString())+" and makho="+int.Parse(r["makho"].ToString()));
					}
					else if (r["loai"].ToString()=="1")
					{
						id=getid(d.user+r["mmyy"].ToString()+".d_ngtrull",d.user+r["mmyy"].ToString()+".d_ngtruct",int.Parse(r["loai"].ToString()),r["ngaysp"].ToString(),int.Parse(r["makhoa"].ToString()),int.Parse(r["makho"].ToString()),int.Parse(r["manguon"].ToString()));
						if (id!="") a.execute_data("update "+d.user+r["mmyy"].ToString()+".d_ngtruct set ketoan="+idct+" where id in ("+id.Substring(0,id.Length-1)+") and manguon="+int.Parse(r["manguon"].ToString())+" and makho="+int.Parse(r["makho"].ToString()));
					}
					else 
					{
						id=getid(d.user+r["mmyy"].ToString()+".d_xuatsdll",d.user+r["mmyy"].ToString()+".d_thucxuat",int.Parse(r["loai"].ToString()),r["ngaysp"].ToString(),int.Parse(r["makhoa"].ToString()),int.Parse(r["makho"].ToString()),int.Parse(r["manguon"].ToString()));
						if (id!="") a.execute_data("update "+d.user+r["mmyy"].ToString()+".d_thucxuat set ketoan="+idct+" where id in ("+id.Substring(0,id.Length-1)+") and manguon="+int.Parse(r["manguon"].ToString())+" and makho="+int.Parse(r["makho"].ToString()));
					}
				}
				else if (r["chon"].ToString().Trim().ToLower()=="false" && decimal.Parse(r["sotien"].ToString())!=0)
				{
					a.execute_data("delete from "+user+".a_ctct"+s_mmyy.Substring(2)+" where id="+long.Parse(r["sotien"].ToString()));
					a.execute_data("delete from "+user+".a_ct"+s_mmyy.Substring(2)+" where id="+long.Parse(r["sotien"].ToString()));
					a.execute_data("delete from "+user+".a_ctk"+s_mmyy.Substring(2)+" where id="+long.Parse(r["sotien"].ToString()));
					if (r["loai"].ToString()=="3") a.execute_data("update "+d.user+r["mmyy"].ToString()+".d_xuatct set ketoan=0 where id="+long.Parse(r["id"].ToString())+" and manguon="+int.Parse(r["manguon"].ToString()));
					else if (r["loai"].ToString()=="2")
					{
						id=getid(d.user+r["mmyy"].ToString()+".bhytkb",d.user+r["mmyy"].ToString()+".bhytthuoc",int.Parse(r["loai"].ToString()),r["ngaysp"].ToString(),int.Parse(r["makhoa"].ToString()),int.Parse(r["makho"].ToString()),int.Parse(r["manguon"].ToString()));
						if (id!="") a.execute_data("update "+d.user+r["mmyy"].ToString()+".bhytthuoc set ketoan=0 where id in ("+id.Substring(0,id.Length-1)+") and manguon="+int.Parse(r["manguon"].ToString())+" and makho="+int.Parse(r["makho"].ToString()));
					}
					else if (r["loai"].ToString()=="1")
					{
						id=getid(d.user+r["mmyy"].ToString()+".d_ngtrull",d.user+r["mmyy"].ToString()+".d_ngtruct",int.Parse(r["loai"].ToString()),r["ngaysp"].ToString(),int.Parse(r["makhoa"].ToString()),int.Parse(r["makho"].ToString()),int.Parse(r["manguon"].ToString()));
						if (id!="") a.execute_data("update "+d.user+r["mmyy"].ToString()+".d_ngtruct set ketoan=0 where id in ("+id.Substring(0,id.Length-1)+") and manguon="+int.Parse(r["manguon"].ToString())+" and makho="+int.Parse(r["makho"].ToString()));
					}
					else 
					{
						id=getid(d.user+r["mmyy"].ToString()+".d_xuatsdll",d.user+r["mmyy"].ToString()+".d_thucxuat",int.Parse(r["loai"].ToString()),r["ngaysp"].ToString(),int.Parse(r["makhoa"].ToString()),int.Parse(r["makho"].ToString()),int.Parse(r["manguon"].ToString()));
						if (id!="") a.execute_data("update "+d.user+r["mmyy"].ToString()+".d_thucxuat set ketoan=0 where id in ("+id.Substring(0,id.Length-1)+") and manguon="+int.Parse(r["manguon"].ToString())+" and makho="+int.Parse(r["makho"].ToString()));
					}
				}
				bUpdate=true;
			}
			if (bUpdate) a.updDtsd("",s_mmyy,iUserid);
			load_grid();
			butTonghop.Focus();
		}

		private string getid(string ll,string ct,int loai,string ngay,int makhoa,int makho,int manguon)
		{
			string id="";
			sql="select distinct a.id from "+ll+" a,"+ct+" b where a.id=b.id and to_char(a.ngay,'dd/mm/yyyy')='"+ngay+"'";
			sql+=" and b.makho="+makho+" and b.manguon="+manguon;
			if (loai==0) sql+=" and a.makhoa="+makhoa;
			else if (loai==1) sql+=" and a.loai="+makhoa;
			else sql+=" and a.maphu="+makhoa;
			foreach(DataRow r in a.get_data(sql).Tables[0].Rows)
				id+=r["id"].ToString().Trim()+",";
			return id;
		}
		private void butKetthuc_Click(object sender, System.EventArgs e)
		{
			a.close();System.GC.Collect();this.Close();
		}


		private void chkChitiet_CheckedChanged(object sender, System.EventArgs e)
		{
			if (this.ActiveControl==chkChitiet)
			{
				a.writeXml("a_thongso","impctx",(chkChitiet.Checked)?"1":"0");
				chkNo.Enabled=chkChitiet.Checked;
				if (!chkChitiet.Checked) chkNo.Checked=false;
			}
		}

		private void chkAll_CheckedChanged(object sender, System.EventArgs e)
		{
			if (this.ActiveControl==chkAll)
				foreach(DataRow r in ds.Tables[0].Select("sotien=0")) r["chon"]=(chkAll.Checked)?true:false;
		}

		private void frmImpxuat_MouseMove(object sender, System.Windows.Forms.MouseEventArgs e)
		{
			if (bClear)
			{
				khoanmuc2.SelectedIndex=khoanmuc3.SelectedIndex=khoanmuc4.SelectedIndex=-1;
				bClear=false;
			}
		}

		private void chkNo_CheckedChanged(object sender, System.EventArgs e)
		{
			if (this.ActiveControl==chkNo) a.writeXml("a_thongso","impctxnoct",(chkNo.Checked)?"1":"0");
		}

		private void butIn_Click(object sender, System.EventArgs e)
		{
			try
			{
				DataSet dsct1=new DataSet();
				int i=dataGrid1.CurrentCell.RowNumber;
				string mmyy=dataGrid1[i,5].ToString();
				int loai=int.Parse(dataGrid1[i,1].ToString());
				int makho=int.Parse(dataGrid1[i,2].ToString());
				int manguon=int.Parse(dataGrid1[i,3].ToString());
				int makhoa=int.Parse(dataGrid1[i,4].ToString());
				long id=long.Parse(dataGrid1[i,6].ToString());
				string ngay=dataGrid1[i,10].ToString();
				string sophieu=dataGrid1[i,9].ToString();
				string tenkho=dataGrid1[i,8].ToString();
				string lydo=dataGrid1[i,13].ToString();
				string ll=d.user+mmyy+".",ct=d.user+mmyy+".",makp=tenkho;
				switch (loai)
				{
					case 0: ll+="d_xuatsdll";ct+="d_thucxuat";makp="Xuất sử dụng";break;
					case 1: ll+="d_ngtrull";ct+="d_ngtruct";makp="Ngoại trú";break;
					case 2: ll+="bhytkb";ct+="bhytthuoc";makp="BHYT";break;
					case 3: ll+="d_xuatll";ct+="d_xuatct";makp="";break;
				}
				if (loai==3)
				{
					sql="select '"+mmyy+"' as mmyy,"+loai+" as loai,'xx/xx/xxxx' as ngay,"+id+" as idct,f.id,b.ma,trim(b.ten)||' '||b.hamluong as ten,";
					sql+=" b.dang,c.ten as tenhang,d.ten as tennuoc,sum(ct.soluong) as soluong,";
					sql+=" sum(0) as dongia,sum(ct.soluong*t.giamua) as sotien,0 as tkno,'' as ttkno,'' as ttknosave ";
					sql+=" from "+ll+" a,"+ct+" ct,"+d.user+".d_dmbd b,"+d.user+".d_dmhang c,"+d.user+".d_dmnuoc d,"+d.user+mmyy+".d_theodoi t,"+d.user+".d_dmnhomkt e,"+user+".a_dmtk f ";
					sql+=" where a.id=ct.id and ct.mabd=b.id and b.mahang=c.id and b.manuoc=d.id and ct.sttt=t.id and b.sotk=e.id and e.ma=f.stk ";
					sql+=" and a.id="+id+" and ct.manguon="+manguon;
					sql+=" group by f.id,b.ma,trim(b.ten)||' '||b.hamluong,b.dang,c.ten,d.ten";
					sql+=" order by ma";
				}
				else
				{
					sql="select '"+mmyy+"' as mmyy,"+loai+" as loai,to_char(a.ngay,'dd/mm/yyyy') as ngay,0 as idct,f.id,b.ma,trim(b.ten)||' '||b.hamluong as ten,";
					sql+=" b.dang,c.ten as tenhang,d.ten as tennuoc,sum(ct.soluong) as soluong,";
					sql+="sum(0) as dongia,sum(ct.soluong*t.giamua) as sotien,0 as tkno,'' as ttkno,'' as ttknosave ";
					sql+=" from "+ll+" a,"+ct+" ct,"+d.user+".d_dmbd b,"+d.user+".d_dmhang c,"+d.user+".d_dmnuoc d,"+d.user+mmyy+".d_theodoi t,"+d.user+".d_dmnhomkt e,"+user+".a_dmtk f";
					sql+=" where a.id=ct.id and ct.mabd=b.id and b.mahang=c.id and b.manuoc=d.id and ct.sttt=t.id and b.sotk=e.id and e.ma=f.stk";
					sql+=" and to_char(a.ngay,'dd/mm/yyyy')='"+ngay+"'";
					if (loai==0)
					{
						sql+=" and a.makhoa="+makhoa+" and a.loai<>3";
						sql+=" and ct.makho="+makho+" and ct.manguon="+manguon;
					}
					else
					{
						if (loai==2) sql+=" and a.maphu="+makhoa;
						else if (loai==1) sql+=" and a.loai="+makhoa;
						sql+=" and ct.makho="+makho+" and ct.manguon="+manguon;
					}
					sql+=" group by to_char(a.ngay,'dd/mm/yyyy'),f.id,b.ma,trim(b.ten)||' '||b.hamluong,b.dang,c.ten,d.ten";
					sql+=" order by ma";
				}
				dsct1=a.get_data(sql);
				if (loai==0)
				{
					sql="select f.id,b.ma,trim(b.ten)||' '||b.hamluong as ten,";
					sql+=" b.dang,c.ten as tenhang,d.ten as tennuoc,sum(-1*ct.soluong) as soluong,";
					sql+=" sum(0) as dongia,sum(-1*ct.soluong*t.giamua) as sotien,0 as tkno,'' as ttkno ";
					sql+=" from "+ll+" a,"+ct+" ct,"+d.user+".d_dmbd b,"+d.user+".d_dmhang c,"+d.user+".d_dmnuoc d,"+d.user+mmyy+".d_theodoi t,"+d.user+".d_dmnhomkt e,"+user+".a_dmtk f ";
					sql+=" where a.id=ct.id and ct.mabd=b.id and b.mahang=c.id and b.manuoc=d.id and ct.sttt=t.id and b.sotk=e.id and e.ma=f.stk";
					sql+=" and to_char(a.ngay,'dd/mm/yyyy')='"+ngay+"' and a.loai=3";
					sql+=" and a.makhoa="+makhoa;
					sql+=" and ct.makho="+makho+" and ct.manguon="+manguon;
					sql+=" group by f.id,b.ma,trim(b.ten)||' '||b.hamluong,b.dang,c.ten,d.ten";
					sql+=" order by ma";
					DataRow r1,r2;
					DataRow [] dr;
					foreach(DataRow r in a.get_data(sql).Tables[0].Rows)
					{
						r1=a.getrowbyid(dsct1.Tables[0],"ma='"+r["ma"].ToString()+"' and id="+long.Parse(r["id"].ToString()));
						if (r1==null)
						{
							r2=dsct1.Tables[0].NewRow();
							r2["id"]=r["id"].ToString();
							r2["ma"]=r["ma"].ToString();
							r2["ten"]=r["ten"].ToString();
							r2["dang"]=r["dang"].ToString();
							r2["tenhang"]=r["tenhang"].ToString();
							r2["tennuoc"]=r["tennuoc"].ToString();
							r2["soluong"]=r["soluong"].ToString();
							r2["sotien"]=r["sotien"].ToString();
							dsct1.Tables[0].Rows.Add(r2);
						}
						else
						{
							dr=dsct1.Tables[0].Select("ma='"+r["ma"].ToString()+"'");
							if (dr.Length>0)
							{
								dr[0]["soluong"]=decimal.Parse(dr[0]["soluong"].ToString())+decimal.Parse(r["soluong"].ToString());
								dr[0]["sotien"]=decimal.Parse(dr[0]["sotien"].ToString())+decimal.Parse(r["sotien"].ToString());
							}
						}
					}
				}
				decimal st=0;
				foreach(DataRow r in dsct1.Tables[0].Rows)
				{
					st+=decimal.Parse(r["sotien"].ToString());
					if (decimal.Parse(r["soluong"].ToString())!=0) r["dongia"]=decimal.Parse(r["sotien"].ToString())/decimal.Parse(r["soluong"].ToString());
				}
				frmReport f=new frmReport(a,dsct1.Tables[0],"d_phieuxuat.rpt",sophieu,ngay,"","",lydo,makp,tenkho,doiso.Doiso_Unicode(Convert.ToInt64(st).ToString()),"","");
				f.ShowDialog();
			}
			catch{}		
		}

        private void c703_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void c705_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void c707_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void label39_Click(object sender, EventArgs e)
        {

        }

        private void c706_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void label50_Click(object sender, EventArgs e)
        {

        }

        private void label38_Click(object sender, EventArgs e)
        {

        }

        private void label36_Click(object sender, EventArgs e)
        {

        }

        private void nhom_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void label6_Click(object sender, EventArgs e)
        {

        }

        private void den_ValueChanged(object sender, EventArgs e)
        {

        }

        private void tu_ValueChanged(object sender, EventArgs e)
        {

        }

        private void label5_Click(object sender, EventArgs e)
        {

        }

        private void label3_Click(object sender, EventArgs e)
        {

        }

        private void label2_Click(object sender, EventArgs e)
        {

        }

        private void label1_Click(object sender, EventArgs e)
        {

        }

        private void dataGrid1_Navigate(object sender, NavigateEventArgs ne)
        {

        }

        private void dataGrid2_Navigate(object sender, NavigateEventArgs ne)
        {

        }

        private void dataGrid3_Navigate(object sender, NavigateEventArgs ne)
        {

        }
	}
}		
